LeetCode test (v2)

Revision 2 of this benchmark created on


Setup

const pairs = [
  { nums: [2,7,11,15], target: 9 },
  { nums: [3,2,4], target: 6 },
  { nums: [3,3], target: 6 },
];
const PAIRS_COUNT = pairs.length;

const COUNT = 100;
const a = new Array(COUNT);
const b = new Array(COUNT);
const c = new Array(COUNT);

const twoSumA = (nums, target) => {
  const map = new Map();
  for(let i = 0; i < nums.length; i++) {
    const num = target - nums[i];
    const part =  map.get(num);
    if (part) return [part.idx, i]
    map.set(nums[i], { val: num, idx: i });
  }
};

const twoSumB = (nums, target) => {
  const numsCount = nums.length;
  const numsMinusOne = numsCount - 1;
  for (let i = 0; i < numsMinusOne; i++)
    for (let j = i + 1; j < numsCount; j++)
      if (nums[i] + nums[j] === target)
        return [i, j];
};

const twoSumC = (nums, target) => {
  let map = {};
  const numsCount = nums.length;
  for (let i = 0; i < numsCount; i++) {
    const comp = target - nums[i];
    if (map[comp] !== undefined)
      return [i, map[comp]];
    else
      map[nums[i]] = i;
  }
};

Test runner

Ready to run.

Testing in
TestOps/sec
LeetCode solution O(n)
for (let i = 0; i < COUNT; i++) {
  for (let j = 0; j < PAIRS_COUNT; j++) {
  	const { nums, target } = pairs[j];
  	a[i] = twoSumA(nums, target);
  }
}
ready
My solution O(n^2)
for (let i = 0; i < COUNT; i++) {
  for (let j = 0; j < PAIRS_COUNT; j++) {
  	const { nums, target } = pairs[j];
  	b[i] = twoSumB(nums, target);
  }
}
ready
Fastest guy solution O(n)
for (let i = 0; i < COUNT; i++) {
  for (let j = 0; j < PAIRS_COUNT; j++) {
  	const { nums, target } = pairs[j];
  	c[i] = twoSumC(nums, target);
  }
}
ready

Revisions

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