44. Two Sum
Difficulty: Easy · Topic: DSA for data engineers
Write two_sum(nums, target): return a tuple (i, j) with i < j and nums[i] + nums[j] == target, or None if there is none. An element cannot be used twice.
If several pairs work, return the one with the smallest j, and for that j the smallest i. It must run in O(n): inputs can have 200,000 numbers.
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
two_sum([2, 7, 11, 15], 9)Expected: (0, 1)
Hints
Hint 1
For each number, the partner it needs istarget - x.Hint 2
Keep a dict from value to the first index where it was seen; look the partner up before adding the current number.Hint 3
Looking up before adding is what stops a number from pairing with itself.Learn the concepts
- Lists, dicts and sets: what each operation costs · 7 min read. Pick the container from the question, and why a set turns an hour-long loop into a second.
More Python problems
- Valid Brackets · Easy
- First Non-Repeating Character · Easy
- Group Anagrams · Medium
- Longest Substring Without Repeats · Medium
- Top K Frequent with a Heap · Medium
- Latest Event at or Before a Time · Medium
- Merge K Sorted Linked Lists · Hard
- Task Order with Cycle Detection · Hard