Topics
(2Sum) Find two indices in a sorted array where elements sum to target
- left starts at
0
, right atn-1
.- If
arr[left] + arr[right] > target
, decrementright
(sum is too large).- If
sum < target
, incrementleft
.- Time: vs. brute-force .
Deduplicate an array in-place
- Sort the array .
- Uses the concept of slow and fast pointers
slow
pointer tracks the last unique element.fast
scans ahead. Whenarr[fast] != arr[slow]
, incrementslow
and copyarr[fast]
.- Time:
3Sum Find all triplets
[a, b, c]
such thata + b + c = 0
- Sort the array .
- Fix
a = arr[i]
, then use two pointers on the subarrayi+1
ton-1
to find pairs(b, c)
such thatb + c = -a
.- Time: vs. brute-force .