Bird
Raised Fist0
DSA Typescriptprogramming~20 mins

Two Sum Problem Classic Hash Solution in DSA Typescript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Two Sum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Two Sum solution?
Given the following TypeScript code for the Two Sum problem, what will be printed when calling twoSum([2, 7, 11, 15], 9)?
DSA Typescript
function twoSum(nums: number[], target: number): number[] {
  const map = new Map<number, number>();
  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];
    if (map.has(complement)) {
      return [map.get(complement)!, i];
    }
    map.set(nums[i], i);
  }
  return [];
}

console.log(twoSum([2, 7, 11, 15], 9));
A[]
B[1, 2]
C[2, 3]
D[0, 1]
Attempts:
2 left
💡 Hint
Think about which two numbers add up to 9 and their indices.
🧠 Conceptual
intermediate
1:00remaining
What is the time complexity of the classic Two Sum hash solution?
Consider the classic Two Sum solution using a hash map. What is the time complexity in Big O notation for this approach?
AO(n)
BO(n log n)
CO(log n)
DO(n^2)
Attempts:
2 left
💡 Hint
Think about how many times the array is traversed and the cost of hash map operations.
🔧 Debug
advanced
2:00remaining
What error does this Two Sum code produce?
Identify the error when running this TypeScript code snippet:
DSA Typescript
function twoSum(nums: number[], target: number): number[] {
  const map = new Map<number, number>();
  for (let i = 0; i <= nums.length; i++) {
    const complement = target - nums[i];
    if (map.has(complement)) {
      return [map.get(complement)!, i];
    }
    map.set(nums[i], i);
  }
  return [];
}

twoSum([1, 2, 3], 4);
ARangeError: Maximum call stack size exceeded
BTypeError: Cannot read property 'undefined' of undefined
CSyntaxError: Unexpected token
DNo error, returns [0, 2]
Attempts:
2 left
💡 Hint
Check the loop condition and array indexing carefully.
🚀 Application
advanced
2:00remaining
What is the output after running this Two Sum variant?
This variant returns the actual numbers instead of indices. What is printed when running this code?
DSA Typescript
function twoSumValues(nums: number[], target: number): number[] {
  const map = new Map<number, boolean>();
  for (const num of nums) {
    const complement = target - num;
    if (map.has(complement)) {
      return [complement, num];
    }
    map.set(num, true);
  }
  return [];
}

console.log(twoSumValues([3, 1, 4, 6], 7));
A[3, 4]
B[1, 6]
C[4, 3]
D[]
Attempts:
2 left
💡 Hint
Look at the order of numbers returned when complement is found.
🧠 Conceptual
expert
1:30remaining
Why is the classic Two Sum hash solution preferred over sorting and two-pointer approach for returning indices?
Choose the best reason why the classic hash map solution is preferred when the problem requires returning original indices of the two numbers.
ASorting is always slower than hash map lookups, so it is never used.
BTwo-pointer approach cannot find pairs that sum to target.
CSorting changes the order, so original indices are lost and must be tracked separately, increasing complexity.
DHash maps use less memory than sorting arrays.
Attempts:
2 left
💡 Hint
Think about what happens to indices when you sort the array.

Practice

(1/5)
1. What is the main purpose of using a hash map in the Two Sum problem classic solution?
easy
A. To store the sum of all pairs
B. To sort the array before searching
C. To store numbers and their indices for quick lookup
D. To reverse the array elements

Solution

  1. Step 1: Understand the role of hash map

    The hash map stores each number as a key and its index as the value for quick lookup.
  2. Step 2: Explain why quick lookup is needed

    Quick lookup helps to find if the complement (target - current number) exists without scanning the entire array again.
  3. Final Answer:

    To store numbers and their indices for quick lookup -> Option C
  4. Quick Check:

    Hash map stores number:index = A [OK]
Hint: Hash map stores values for instant complement check [OK]
Common Mistakes:
  • Thinking hash map sorts the array
  • Trying to store sums instead of indices
  • Using hash map to reverse elements
2. Which of the following TypeScript code snippets correctly initializes an empty hash map for the Two Sum problem?
easy
A. const map = new Map();
B. const map = {};
C. const map = new Array();
D. const map = new Set();

Solution

  1. Step 1: Identify correct hash map initialization

    In TypeScript, new Map<number, number>() creates a map with number keys and values.
  2. Step 2: Explain why other options are incorrect

    {} is an object but lacks type safety; new Array() is an array, not a map; new Set() stores unique values, not key-value pairs.
  3. Final Answer:

    const map = new Map<number, number>(); -> Option A
  4. Quick Check:

    Use Map<number, number> for hash map [OK]
Hint: Use Map<number, number> for key-value pairs [OK]
Common Mistakes:
  • Using Set instead of Map
  • Using Array instead of Map
  • Using plain object without type safety
3. What will be the output of the following TypeScript code for the input array [2, 7, 11, 15] and target 9?
function twoSum(nums: number[], target: number): number[] {
  const map = new Map();
  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];
    if (map.has(complement)) {
      return [map.get(complement)!, i];
    }
    map.set(nums[i], i);
  }
  return [];
}

console.log(twoSum([2, 7, 11, 15], 9));
medium
A. [1, 2]
B. []
C. [2, 3]
D. [0, 1]

Solution

  1. Step 1: Trace the loop and map updates

    i=0: map={}, complement=9-2=7, map.has(7)? No, map.set(2,0).
    i=1: complement=9-7=2, map.has(2)? Yes, index=0, return [0,1].
  2. Step 2: Confirm returned indices

    Indices 0 and 1 correspond to numbers 2 and 7 which sum to 9.
  3. Final Answer:

    [0, 1] -> Option D
  4. Quick Check:

    Indices of 2 and 7 = [0, 1] [OK]
Hint: Check complement in map before adding current number [OK]
Common Mistakes:
  • Returning values instead of indices
  • Not checking map before insertion
  • Returning empty array incorrectly
4. Identify the bug in this TypeScript Two Sum implementation:
function twoSum(nums: number[], target: number): number[] {
  const map = new Map();
  for (let i = 0; i <= nums.length; i++) {
    const complement = target - nums[i];
    if (map.has(complement)) {
      return [map.get(complement)!, i];
    }
    map.set(nums[i], i);
  }
  return [];
}
medium
A. map.set should be called before checking complement
B. Loop condition should be < instead of <=
C. Return statement should return values instead of indices
D. Complement calculation is incorrect

Solution

  1. Step 1: Analyze loop condition

    The loop uses i <= nums.length, which causes out-of-bounds access at last iteration.
  2. Step 2: Correct loop condition

    Change to i < nums.length to avoid accessing undefined element.
  3. Final Answer:

    Loop condition should be < instead of <= -> Option B
  4. Quick Check:

    Loop must stay within array bounds [OK]
Hint: Use < not <= for array index loops [OK]
Common Mistakes:
  • Off-by-one error in loop condition
  • Swapping order of map.set and map.has
  • Returning values instead of indices
5. Given the input array [3, 3, 4, 5] and target 6, what will the Two Sum classic hash solution return?
function twoSum(nums: number[], target: number): number[] {
  const map = new Map();
  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];
    if (map.has(complement)) {
      return [map.get(complement)!, i];
    }
    map.set(nums[i], i);
  }
  return [];
}

console.log(twoSum([3, 3, 4, 5], 6));
hard
A. [0, 1]
B. [1, 2]
C. [2, 3]
D. []

Solution

  1. Step 1: Trace the loop and map updates with duplicates

    i=0: map={}, complement=6-3=3, map.has(3)? No, map.set(3,0).
    i=1: complement=6-3=3, map.has(3)? Yes, index=0, return [0,1].
  2. Step 2: Confirm correct pair with duplicates

    Even with duplicates, first pair indices 0 and 1 sum to 6.
  3. Final Answer:

    [0, 1] -> Option A
  4. Quick Check:

    Duplicates handled, indices [0,1] sum to target [OK]
Hint: Duplicates allowed; first matching pair returned [OK]
Common Mistakes:
  • Ignoring duplicates and returning wrong indices
  • Returning empty array incorrectly
  • Confusing values with indices
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard