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.
Example 1:
Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6 Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6 Output: [0,1]
Constraints:
2 <= nums.length <= 104-109 <= nums[i] <= 109-109 <= target <= 109O(n2) time complexity?When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are given a target number and a list of items with numbers written on them. The brute force approach is the most straightforward way to solve this by testing every possible pair of items to see if their combined numbers add up to the target.
Here's how the algorithm would work step-by-step:
def two_sum_brute_force(numbers_list, target_value):
# Exhaustively test every possible pair since no pre-computation is used
for current_index in range(len(numbers_list)):
for next_index in range(current_index + 1, len(numbers_list)):
# Verify if the combined pair sum matches the desired target exactly
if numbers_list[current_index] + numbers_list[next_index] == target_value:
return [current_index, next_index]
return []Instead of checking every possible pair, the optimal approach is like keeping a running memory of the numbers you have already looked at. As you examine each number, you instantly calculate what partner number you need to reach your target and check your memory to see if you have already seen it.
Here's how the algorithm would work step-by-step:
def two_sum(numbers_list, target_total):
# Start with a completely blank memory to record the numbers you visit along the way.
visited_numbers_map = {}
for current_index, current_number in enumerate(numbers_list):
# Figure out what missing partner number would need to be added to your current number to hit the target total.
required_partner_number = target_total - current_number
# Check your memory to see if you have previously encountered that exact partner number.
if required_partner_number in visited_numbers_map:
return [visited_numbers_map[required_partner_number], current_index]
visited_numbers_map[current_number] = current_index
return []| Case | How to Handle |
|---|---|
| Empty array or array with only one element | Return an empty array or throw an exception immediately since a pair cannot be formed. |
| Array with exactly two elements that sum to the target | The first element is stored in the map and the second element completes the pair on the second iteration. |
| Array containing negative numbers and zeros | The hash map approach naturally handles negative numbers and zeros without requiring any special mathematical adjustments. |
| Duplicate numbers in the array that could form the target | The hash map checks for the complement before inserting the current element, preventing improper self-matching. |
| Extremely large array with maximum possible constraints | A single-pass hash map solution scales efficiently with an optimal O(n) time and space complexity. |
| No valid two sum solution exists in the array | The function gracefully returns an empty result or null after checking all elements without finding a match. |
| Multiple valid pairs exist that add up to the target | The algorithm returns the indices of the first valid pair encountered during the single pass traversal. |
| Very large integer values approaching limits causing potential overflow | Languages like Java or C++ require careful range checks if complements exceed standard integer boundaries. |