Problem Category:: Array, Hash table Neetcode Category:: Arrays and Hashing

https://leetcode.com/problems/two-sum/description/

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target

  • You may assume that each input would have exactly one solution, and you may not use the same element twice
  • You can return the answer in any order

Optimal

Dictionary

We want to maintain a mapping of each element to its index, and require quick lookup - therefore a Hash table based data structure should be used (e.g.: Dictionary)

  • Time complexity: - one traversal, average lookups
  • Space complexity: - dictionary

Others

Brute force

nested for loop to check all

Notes

  • Sorting the list, even when keeping track of the original indices, doesn’t help us improve from as the two numbers that sum to target are not necessarily adjacent to each other when sorted