Taro Logo

Two Sum

#1 Most AskedEasy
181 views
Topics:
Arrays

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 <= 109
  • Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

Solution


Clarifying Questions

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:

  1. Is it guaranteed that a valid solution always exists, or what should we return if no two numbers sum up to the target?
  2. Can the same element in the array be used twice to reach the target sum?
  3. If there are multiple valid pairs that add up to the target, does it matter which pair of indices I return?
  4. Can the input array contain negative numbers and zeros, or are we strictly dealing with positive integers?
  5. What should the return format be? Should it be an array, a tuple, or something else containing the two indices?

Brute Force Solution

Approach

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:

  1. Pick the very first item on the list.
  2. Pair this item with every single other item that comes after it, one by one.
  3. For every pair you make, add the two numbers together and check if the total matches your target number.
  4. If you find a pair that adds up to the target, you have found your answer and can stop.
  5. If that first item does not form a winning pair with any other item, move on to the second item on the list.
  6. Repeat the process by pairing this second item with every item that comes after it and check the total.
  7. Continue this exhaustive process of picking each item and trying it with all subsequent items until you find the winning pair.

Code Implementation

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 []

Big(O) Analysis

Time Complexity
O(n²) – To analyze the runtime, let n be the total number of items in the input list. For each of the n items picked in the outer step, the algorithm iteratively pairs it with every subsequent item in the inner step. Specifically, we check n-1 items for the first pick, n-2 for the second, and so on, resulting in n * (n-1) / 2 total pair checks. Discarding constants and lower-order terms, this quadratic growth simplifies to a Big O time complexity of O(n²).
Space Complexity
O(1) – The brute force approach described in the plain English steps does not utilize any auxiliary data structures like hash maps or temporary lists. The algorithm only uses a few primitive variables for loop iteration and index tracking, which require a constant amount of extra memory regardless of the input size. Therefore, as the input size N grows, the auxiliary space complexity remains strictly constant.

Optimal Solution

Approach

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:

  1. Start with a completely blank memory to record the numbers you visit along the way.
  2. Look at the first number in the list.
  3. Figure out what missing partner number would need to be added to your current number to hit the target total.
  4. Check your memory to see if you have previously encountered that exact partner number.
  5. If that partner number is already in your memory, you have successfully found your matching pair and your mission is complete.
  6. If that partner number is not in your memory yet, take your current number and store it away in your memory for future checks.
  7. Move on to the next number in the list and repeat the process until the matching pair is found.

Code Implementation

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 []

Big(O) Analysis

Time Complexity
O(n) – To find the two sum, we iterate through the list of n numbers exactly once from left to right. During each iteration, we perform a constant time hash map lookup to check if the complement partner already exists in our memory. If the partner is not found, we insert the current number and its index into the hash map in constant time. Therefore, the total operations scale linearly with the input size n, simplifying to O(n).
Space Complexity
O(N) – The auxiliary space is driven by the hash map described in the plain English explanation as your running memory to record the numbers you visit along the way. As you iterate through the list of size N, in the worst-case scenario where the pair is found at the very end or not at all, you store every single number and its index in this hash map. Therefore, the memory consumed by this data structure grows in direct proportion to the input size N, resulting in a linear space complexity of O(N).

Edge Cases

Empty array or array with only one element
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The hash map checks for the complement before inserting the current element, preventing improper self-matching.
Extremely large array with maximum possible constraints
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Languages like Java or C++ require careful range checks if complements exceed standard integer boundaries.
0/1037 completed