Target Two Sum
Given an array of unsorted unique integers, write a function getTargetIndexes that returns an array of arrays of the index pairs for each of the two numbers that add up to the target.
- Prioritize run time complexity over memory
- An item can not match with itself
- The same pair of indexes should only be included once
- The order of the returned array and its items does not matter
Breakdown
Approach and test strategy
All original-index pairs using earlier-value lookup
Read the approach, boundary cases, and complexity
The input values are unique and the output contains every matching pair of distinct original indexes. Before storing the current value, look up its complement among earlier positions. This order prevents matching the current position with itself. A map lookup must distinguish a stored index zero from an absent key. Sorting in place would change index meaning and violate input preservation.
Cases to check
- Test an empty list, a missing answer, and a complement stored at index zero.
- Include negative values and zero.
- Compare all pairs with an independent nested-loop reference, normalizing only irrelevant pair order.
Cost model
With expected constant-time hash operations, scanning n unique values takes expected O(n) time plus emitted output and O(n) retained map entries. Fixed-width complement subtraction needs a safe numeric policy.
Programming languages for this lesson
Starter code and reference implementations are available in:
The editor shows which of these languages can run on this deployment.
Validate My Answer
You can do this brute force, but it will be the worse solution at O(n2) time.
Keep the constraints in mind. You don't have to worry about duplicate values in the array.
By adding another data structure, you can do this in O(n) time and O(n) space.
Remember you can't add a number to itself (ie. the solution is the same index twice). However, you can add a number to zero. For example,
array = [4,8,0],target = 8: You can't say[0,0]for4+4, but you can say[1,2]for8+0.Does your solution handle negative numbers?
Does your solution handle an empty array input?
Make sure your solution doesn't include repeated indexes. For example, if you already have
[1,4]in your results, you shouldn't also have[4,1]. However, having either one of those is acceptable based on the constraints.
Target Two Sum
Given an array of unsorted unique integers, write a function getTargetIndexes that returns an array of arrays of the index pairs for each of the two numbers that add up to the target.
- Prioritize run time complexity over memory
- An item can not match with itself
- The same pair of indexes should only be included once
- The order of the returned array and its items does not matter