Google 2020 Whiteboard Question

JavaScript performance comparison

Test case created by Jasperrr91

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Joey
const twoSum = (arr, target) => {
  const hashTable = {};
  populateTable(hashTable, arr);

  for (let i = 0; i < arr.length; i++) {
    const desiredValue = target - arr[i];
    if (validValueExists(desiredValue, hashTable, i)) {
      return [i, hashTable[desiredValue]];
    }
  }

  return [-1, -1];
};

const validValueExists = (desiredValue, hashTable, currentIndex) => {
  return (
    // Make sure there exists a key with `desiredValue`.
    hashTable.hasOwnProperty(desiredValue)
    // Make sure we aren't re-using the same index.
    && hashTable[desiredValue] !== currentIndex
  );
}

const populateTable = (hashTable, arr) => {
  for (let i = 0; i < arr.length; i++) {
    hashTable[arr[i]] = i;
  }
}

twoSum([2, 1, 4, 3], 6);
twoSum([2, 7, 11, 15], 9);
pending…
Jasper
const twoSum = (arr, target) => {
	const hashTable = {};
  
  for (let i = 0; i < arr.length; i++) {
    const desiredValue = target - arr[i];
    if (hashTable[desiredValue] !== undefined) {
    	return [hashTable[desiredValue], i];
    }
    hashTable[arr[i]] = i;
  }
}


twoSum([2, 1, 4, 3], 6);
twoSum([2, 7, 11, 15], 9);
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments