Problem 01 - Two Sum
Problem
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Examples
Constraints
2 ≤
nums.length
≤ 10⁴–10⁹ ≤
nums[i]
,target
≤ 10⁹Exactly one valid pair exists.
You can’t use the same element twice.
Follow-up: Can you come up with an algorithm that is less than O(n
2
)
time complexity?
Start Code
Answer
Brute-Force (O(n²))
That's easy, right? just check every possible pair:
Why it works: We compare each element
nums[i]
with every othernums[j]}
that comes after it.The downside: Two nested loops → O(n²) time, which can be slow on large inputs.
One-Pass Hash Map (O(n))
We can do better by trading space for time. As we scan the list, we store each value’s index in a hash map and look up its needed complement on the fly:
Key idea: For each
num
, ask “Have I already seentarget – num
?”Why it’s fast: One pass through the array, constant-time hash lookups → O(n) time and O(n) space (memory).
Lessons Learned
Hash maps to the rescue: They turn nested-loop searches into single-pass lookups.
Space–time trade‐off: Using extra memory (the map) can dramatically reduce runtime.
Last updated