Two Sum LeetCode

Key takeaways:

  • The Two Sum problem is a foundational exercise in algorithms, with applications in finance, statistics, and data analysis, requiring efficient computation.

  • Given an array nums and a target, find two indices i and j such that nums[i] + nums[j] == target. For example, identify two items in a shop with combined costs matching a fixed budget, e.g., $10.

  • Use a dictionary to store numbers and their indices, checking for the complement (target - num) in constant time during a single array traversal.

  • Time complexity is O(n)O(n) and space complexity is O(n)O(n), making it efficient for large inputs.

Problem-solving carries substantial implications and LeetCode’s Two Sum is a key problem in algorithms. This challenge swiftly pinpoints pairs in a numeric array that collectively meet a specific target value. It’s similar to practical applications in financial analytics, statistical computations, and network data analysis, highlighting the necessity for rapid and exact computational solutions. Now, let’s consider a scenario to understand the problem:

Imagine stepping into a candy shop with a budget of $10. The shelves are lined with colorful candies, each with its price tag. The mission is clear: find a pair of candies whose combined cost equals $10 with the constraint that only one candy can be picked from one jar. This visual example lays the foundation for the concepts we’ll explore further in the problem statement.

Problem statement

We are given an array of integers, nums, and an integer target. The task is to find two distinct indexes, i and j, in the array such that nums[i] + nums[j] equal the target. There is guaranteed to be exactly one solution.

Some important points to consider while solving this problem are:

  1. We can assume that each input would have exactly one solution, and we may not use the same element twice.

  2. We can return the answer in any order.

  3. The length of the nums array is between 22 and 10310^3.

  4. Each element nums[i] is between 109−10^9and 10910^9.

  5. The target is between 109−10^9 and 10910^9.

canvasAnimation-image
1 of 2

Note: In the context of our current scenario, positive values are utilized exclusively. Nonetheless, it is essential to acknowledge that in diverse situations, negative values may also be encountered.

Knowledge test

Now that we’ve grasped the problem, let’s assess our understanding by identifying pairs in the following example that can collectively achieve our target value:

Knowledge test
Knowledge test

Algorithm to solve Two Sum LeetCode problem

Now that we’ve understood the problem let’s understand it programmatically. The function twoSum is designed to find two numbers in a list nums that add up to a specific target number target.

Here’s how it works:

  1. We start by creating an empty dictionary num_dict. This will store each number from the list and its corresponding index.

  2. We then iterate over the list of numbers. For each number, we calculate its complement (i.e., target - num).

  3. If the complement is already in num_dict, it means we have found a pair of numbers that add up to the target. We return the indices of these two numbers.

  4.  If the complement is not in num_dict, we store the current number and its index in num_dict. This will be used for future iterations.

  5. If we finish iterating over the list and haven’t found a pair that adds up to the target, we return None.

Two Sum algorithmic approach
Two Sum algorithmic approach
1 of 8

Coding example

Let’s have a look at the code for the algorithm we just discussed:

def twoSum(nums, target):
num_dict = {} # Dictionary to store the complement of each number
for i, num in enumerate(nums):
complement = target - num
if complement in num_dict:
# Found a pair that adds up to the target
return [num_dict[complement], i]
num_dict[num] = i # Store the current number and its index
# If no solution is found
return None
arr = [2, 7, 11, 15]
target_sum = 9
result = twoSum(arr, target_sum)
print("Array", arr)
print("target", target_sum)
if result:
print(f"\nIndices of the two numbers that add up to {target_sum}: {result}")
print(f"Numbers: {arr[result[0]]} and {arr[result[1]]}")
else:
print(f"No solution found for the target sum {target_sum}.")

Code explanation

  • Line 1: We defined the twoSum function, which takes two parameters: nums, an array of integers, and the target which have the target value.

  • Line 3: We defined an empty dictionary with the name of num_dict to store the complement of each number along with its index.

  • Lines 5–10: In this section, the code efficiently iterates through the array using a for loop, checking for complements in a dictionary. If a complement is found, it returns the indices of the pair that add up to the target sum. If not, it stores the current number and index in the dictionary for subsequent iterations.

  • Lines 19–25: This code block checks if a solution exists for the two-sum problem and prints the result accordingly. If a solution is found, it prints the indices and actual numbers of the pair that adds up to the target sum. If no solution is found, it prints a message “No solution found for the target sum {target_sum}.”.

Time complexity

The time complexity of the provided twoSum function is O(n)O(n), where nn is the length of the input list nums. This is because the function iterates over the list nums exactly once. In each iteration, it performs constant time operations such as computing the complement of the current number, checking if the complement is in the dictionary num_dict, and updating num_dict.

Space complexity

The space complexity of the function is also O(n)O(n)because in the worst case the dictionary num_dict ends up storing all elements in the list nums.

Additional resources

To strengthen your skills in coding interviews, consider the Grokking the Coding Interview Patterns course. This course focuses on essential coding patterns and algorithms frequently tested in technical interviews, offering hands-on practice and in-depth explanations. It’s an excellent way to build a solid foundation for tackling coding interview questions and mastering patterns like sliding windows, two pointers, and subsets.

To further strengthen your coding skills and boost your technical interview preparation, here are some LeetCode problems to practice:

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is the Two Sum problem?

The Two Sum problem asks us to find two indices in an integer array that sum to a given target value, a common problem in algorithm challenges.


How is the Two Sum problem applicable in real life?

This problem applies to real-world cases, like finance and inventory management, where quick calculations to match specific sums are needed.


Why use a hashmap in solving Two Sum?

Hashmaps allow O(1)O(1) lookups, making it faster to find complementary values for each number, improving efficiency to O(n)O(n) time complexity.


What are the time and space complexities of the solution?

The solution runs in O(n)O(n) time complexity and requires O(n)O(n) space for the hashmap to store each element’s index.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved