Easy Problems

1. Two Sum

What will be learned

  • Learn to use hash tables to solve problems efficiently.

Solutions

Brute Force

We will check every pairs

Implementation

function twoSum(nums: number[], target: number): number[] {
  for(let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if(nums[i] + nums[j] === target) {
        return [i, j]
      }
    }
  }
};

One-pass Hash Table

In this approach, we trade space for time, or I like to say, we trade memory for speed.

function twoSum(nums: number[], target: number): number[] {
    const map = {};
    for(let i  = 0; i < nums.length; i++) {
        const num = nums[i]
        const complement = target - num;
        if(complement in map) return [i, map[complement]]
 
        map[num] = i;
    }
};

Two-pass Hash Table

function twoSum(nums: number[], target: number): number[] {
    const map = {};
    for(let i = 0; i < nums.length; i++) {
        map[nums[i]] = i;
    }
 
    for(let i = 0; i < nums.length; i++) {
        const complement = target - nums[i];
        if(map[complement] !== undefined && map[complement] !== i) { 
            return [i, map[complement]]
        }
    }
};

Video Solution

Last Update: 12:08 - 16 April 2024
Array
Hash Table

On this page