Member-only story
Two Sum Problem (LeetCode Problem-Solving — 3)
4 min readJan 13, 2025
Find two indices of numbers in an array nums such that their sum equals the given target. Each input is guaranteed to have exactly one solution, and you cannot use the same element twice.
My articles are open for everyone; non-member readers can read the article by clicking this link.
1 — Solution with Explanation
To solve the problem efficiently, we can use a hash map (object in JavaScript) to keep track of the numbers we’ve seen so far and their indices. This allows us to achieve a time complexity of O(n), which is much faster than the brute-force approach.
2 — Steps to Solve
1. Iterate through the array:
- For each number
nums[i]
, calculate thecomplement
(i.e., the value that needs to be added tonums[i]
to reach the target).
2. Check if the complement exists in the hash map:
- If the complement exists, return the indices of
nums[i]
and thecomplement
.
3. Store the current number in the hash map:
- Add the current number
nums[i]
to the hash map along with its index. This helps us track numbers we’ve already processed.