1. Two Sum
On LeetCode ->Problem¶
Return the indices of two distinct elements in nums whose sum is target.
Example:
Key trick¶
Use a hash map from value to index while scanning once.
- For each
xat indexi, look fortarget - xin the map. - If found, return the stored index and
i. - Otherwise store
x -> i.
Trap¶
Common mistakes:
- Using the same element twice.
- Storing before checking, which breaks cases like
nums=[3,3], target=6. - Returning values instead of indices.
- Writing the \(O(n^2)\) double loop and missing the follow-up.
Why is it interesting?¶
It tests the classic move from brute force to hashing.
- Naive: check all pairs.
- Better: trade memory for time and get \(O(n)\).
Python solution¶
class Solution:
def twoSum(self, nums: list[int], target: int) -> list[int]:
seen = {} # value -> index
for i, x in enumerate(nums):
y = target - x
if y in seen:
return [seen[y], i]
seen[x] = i
Comment on my solution¶
Your solution is correct, but it is quadratic.
- Time complexity is \(O(n^2)\).
- The expected interview improvement is the hash map solution with \(O(n)\) time and \(O(n)\) space.
Small notes:
- Your test should prefer cases with a unique valid answer.
- Comparing with
sorted(...)is fine if order does not matter. - The case
[1, 3, 4, 5, 8, 8, 5], 10is not ideal because it has multiple valid answers.
import pytest
class Solution:
def twoSum(self, nums: list[int], target: int) -> list[int]:
for i in range(len(nums) - 1):
for j in range(i + 1,len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
@pytest.mark.parametrize(
("nums", "target", "output"),
[
([2,7,11,15], 9, [0,1]),
([3,2,4], 6, [1,2]),
([3,3], 6, [0, 1]),
([1, 3, 4, 5, 8, 8, 5], 10, [3, 6])
]
)
def test_twoSum(nums, target, output):
assert sorted(Solution().twoSum(nums, target)) == sorted(output)