Two Sum
Table of contents
Problem
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
With a hash map
- Create a hash map that maps each number in
numsto its index. - Go through the elements of
numand check iftarget - num[i]is in the map. - If you found a match, return the indices
iandhashmap[target - num[i]].
This approach is $O(n)$.
With sorting
- Sort the array in ascending order.
- Initialize two pointers
iandjat the beginning and the end of the array, respectively. - If
nums[i] + nums[j] > target, decrementj. - If
nums[i] + nums[j] < target, incrementi. - If
nums[i] + nums[j] == target, returniandj.
The caveat is i and j are not the indices of the original array. You need to find the indices of nums[i] and nums[j] in the original array.
This approach is $O(n \log n)$ because of the sorting.