Two Sum Problem on LeetCode in C++

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

LeetCode's Two Sum issue requires you to find two values in an array that add up to a specific objective. In C++, you can address this problem quickly by utilising a hash map to monitor the elements as you traverse the array. Begin by iterating over the array, checking for each element and whether the complementary value required to achieve the goal exists in the hash map. If found, return the indices. This technique guarantees a temporal complexity of less than O(n^2). This challenge not only tests your computational abilities but also encourages an optimised method, making it an excellent exercise for learning C++ coding.

Problem Description

On LeetCode, the Two Sum challenge is about finding two numbers in an array that add up to a particular objective. It's a traditional coding exercise that challenges your problem-solving abilities. Let's break down the problem and look at a basic yet effective C++ solution.

Problem Breakdown

  • Input: An array of integers nums and targeted integer.
  • Output: Return the indices of the two numbers that add up to the target.

Example:

Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: nums[0] + nums[1] == 9, so we return [0, 1].

Example Scenarios

Let's understand the problem with a few examples:

Example 1:

  • Input: nums = [2,7,11,15], target = 9
  • Output: [0,1]
  • Explanation: nums[0] + nums[1] == 9, hence the return of [0, 1].

Example 2:

  • Input: nums = [3,2,4], target = 6
  • Output: [1,2]
  • The sum of nums[1] + nums[2] equals the target of 6.

Example 3:

  • Input: nums = [3,3], target = 6
  • Output: [0,1]
  • In this case, both elements are the same, and their sum meets the target.

Approaches

  1. Brute Force: The simplest approach is to examine all possible pairings of integers in the array. This has a temporal complexity of O(n^2)because each element must be compared with every other element.
  2. Two Pass Hash Table: For a more efficient approach, use a hash table to store the difference between the goal and each element. This decreases the temporal complexity of a two-pass iteration across the array to O(n).
  3. One run Hash Table: Additional optimisation may be achieved by combining the search for the complement and insertion into the hash table in a single run. This yields a one-pass hash table technique with O(n) time complexity.

Constraints and Follow-up

The problem constraints specify the length of our array (nums.length), the range of values in the array (-109 <= nums[i] <= 109), and the target value (-109 <= target <= 109). This ensures that only one valid answer exists.

The intriguing follow-up question challenges us to devise an algorithm with a time complexity of less than O(n^2). This allows exploration into more advanced algorithms and data structures to achieve a more optimal solution.

The Two Sum issue is a fantastic chance to practise different problem-solving methodologies in C++. Exploring these approaches, which range from the fundamental brute force method to highly optimised hash table solutions, helps us understand algorithmic efficiency. The follow-up question challenges us to look beyond the apparent solutions, fostering innovation and originality in algorithm creation.

Solution 1: Brute Force Approach

The brute force method involves examining every possible pair of integers in the array to verify if their total equals the target. The algorithm iterates across the array using nested loops, examining each pair of items. If a pair with the specified sum is discovered, the indices are returned.

Algorithm

  1. Use nested loops to cycle through each pair of entries in the array.
  2. Determine if the total of the current pair equals the objective.
  3. If a matched pair is discovered, return the indices of both numbers.

Code:

Example:

Time Complexity

The time complexity of the given algorithm is O(n^2), where n is the number of elements in the input array. This is because the algorithm uses nested loops to iterate through each pair of elements in the array. The outer loop runs (n-1) times, and for each iteration of the outer loop, the inner loop runs (n-i-1) times. Therefore, the total number of comparisons is given by the sum of the series (n-1) + (n-2) + ... + 1, which simplifies to n * (n-1) / 2. Asymptotically, this is O(n^2).

Space Complexity

The space complexity of the algorithm is O(1), meaning it uses constant space. The space required by the algorithm is independent of the input size. The only variables used are integers for the loop counters and a constant number of other variables (such as the target variable and the result vector). There is no additional space consumption proportional to the input size.

Follow-Up

To attain a temporal complexity less than O(n^2), a more optimised solution employing hash tables can be considered. The "Two-Pass Hash Table" solution trades time complexity for space complexity. This issue is beyond the scope of this essay but offers an intriguing option for additional investigation.

In conclusion, the brute force strategy is a simple solution to the Two Sum issue, but there are more efficient algorithms to investigate for bigger datasets.

Solution 2: Two-Pass Hash Table

LeetCode's Two Sum issue requires us to discover two values in an array that add up to a specific objective. In this solution, we will look at an efficient method that uses a Two-Pass Hash Table technique in C++. This approach maintains accuracy while simultaneously optimising temporal complexity, surpassing the O(n^2) limit.

Algorithm Overview

The key to an efficient solution lies in using a Two-Pass Hash Table. In the first run, we'll fill the hash table with array elements and matching indexes. Then, in the second pass, we'll look for the complement of each entry in the hash table to discover the pair that equals the goal.

Algorithm Steps

  1. Initialize Hash Table: Create an empty hash table to store the array elements and their indices.
  1. First Pass - Populate Hash Table: Traverse the array and insert each required element along with its index into the hash table.
  1. Second Pass - Find Complements: Traverse the array continuously and search for the complement of each element in the hash table.
  1. Handle Constraints: Given the constraints, we can configure that only one valid answer exists.

Code: Below is the C++ code implementing the Two-Pass Hash Table approach for the Two Sum Problem.

Time Complexity

The time complexity of the Two-Pass Hash Table approach for the two-sum Problem is O(n), where n is the number of elements in the input array.

  • First Pass (Hash Table Initialization): In the first pass, we traverse the array once and insert each element along with its index into the hash table. The insertion operation for each element in the hash table has an average time complexity of O(1), assuming a good hash function and efficient hash table implementation. Therefore, the time complexity of the first pass is O(n).
  • Second Pass (Finding Complements): In the second pass, we again traverse the array once. For each element, we check for the complement in the hash table. The lookup operation in a hash table also has an average time complexity of O(1). Therefore, the time complexity of the second pass is O(n).

Since both passes have linear time complexity, the overall time complexity of the algorithm is O(n).

Space Complexity

The space complexity of the Two-Pass Hash Table approach is O(n), where n is the number of elements in the input array.

  • Hash Table: We use a hash table to store the array elements and their indices. In the worst case, where all elements are distinct, the hash table will have n entries. The space complexity of the hash table is O(n).
  • Other Variables: The algorithm uses a constant amount of additional space for variables like loop counters and temporary values, contributing only a constant factor to the space complexity.

Therefore, the overall space complexity is dominated by the hash table, and it is O(n).

This Two-Pass Hash Table solution fits the restrictions of the Two Sum Problem and achieves a temporal complexity less than O(n^2). By efficiently using the hash tables, the technique provides a scalable and performant approach for determining the indices of two integers that add up to the specified objective.

Solution 3: One-Pass Hash Table

Are you ready to explore an efficient solution to the Two Sum Problem utilising a One-Pass Hash Table? Great! This approach not only delivers a clear and straightforward answer but also has a time complexity of less than O(n^2).

The Two Sum Problem is identifying two integers in an array that add up to a specific objective. The purpose is to retrieve the indices of these integers. Assuming there is always one acceptable solution and no duplication of parts, this problem necessitates a time complexity-optimizing technique.

The One-trip Hash Table approach makes use of the efficiency of hash tables to solve the problem in a single trip across the array.

Algorithm

  1. Set up an empty hash table: Create a hash table to hold the array's items and indexes.
  2. Iterate the array: As you work your way through the array, remove each element from the goal to determine its complement. Check whether this complement exists in the hash table.
  3. Handle matches: If the complement is found then return the indices of the current element and its complement from the hash table. Otherwise, add the current element back to the hash table.

Code Let's translate this approach into C++ code:

Example Let's test our solution with the provided examples:

Time Complexity

The One-Pass Hash Table approach to the Two Sum Problem has a time complexity of O(n), where n is the number of elements in the array. This efficiency is achieved by iterating through the array only once. During each iteration, constant-time operations are performed, such as checking and updating the hash table. The key insight here is that the hash table allows constant-time average case lookups, making the overall time complexity linear concerning the size of the input array.

In the worst-case scenario, where there is no solution, or the solution is located at the end of the array, the algorithm still makes a single pass through all elements. Therefore, it maintains its O(n) time complexity.

Space Complexity

The space complexity of this algorithm is O(n), where n is the number of elements in the array. This is because, in the worst-case scenario, the hash table may need to store all elements of the array. Each element's value and its corresponding index are stored in the hash table, and the size of the hash table grows with the number of elements in the array.

In the best-case scenario, where a solution is found early in the array, the space complexity is still O(n) since the hash table would store at least one element and its index. Overall, the space complexity is directly proportional to the size of the input array.

Congratulations! You've just looked into a One-Pass Hash Table solution to the Two Sum Problem. This strategy is efficient with a temporal complexity of less than O(n^2), making it a valuable tool for handling comparable difficulties.

Step-By-Step Explanation

Let's step by step analyze the One-Pass Hash Table solution for the Two Sum Problem step by step with detailed code comments.

Now, let's delve into the step-by-step explanations:

1. Include Necessary Libraries

These libraries are essential for using unordered maps and vectors in C++.

2. Function Declaration

Declare a function named twoSum that takes a vector of integers (nums) and an integer (target) as parameters, and returns a vector of integers.

3. Create Hash Table

Initialize an unordered map (hashTable) to store elements from the array along with their indices.

4. Iterate Through the Array

Start a loop to iterate through each element of the array nums.

5. Calculate Complement

Calculate the complement for the current element by subtracting it from the target value.

6. Check Hash Table for Complement

Check if the complement exists in the hash table. If found, return the indices of the current element and its complement.

7. Add Element to Hash Table

If the complement is not found, add the current element and its index to the hash table.

8. Handle No Solution

If no solution is found after iterating through the array, return an empty vector or handle it according to your requirements.

Example Usage

Use the twoSum function to find solutions for specific examples and print the results.

To summarise, this method solves the Two Sum Problem effectively by using a One-Pass Hash Table. The comments give detailed explanations for each critical step in the implementation, allowing developers to better understand and apply the solution.

Conclusion

  • The brute force technique is a basic solution to the Two-sum issue that involves thoroughly verifying every pair of integers in the array. Although simple, it has a temporal complexity of O(n^2), making it less efficient for big datasets.
  • The two-pass strategy uses hash tables, with the first pass populating the table and the second looking for complements. This finds a compromise between efficiency and simplicity, although it somewhat increases space complexity.
  • The one-pass hash table strategy improves performance by traversing the array once and dynamically maintaining a hash table. It is a popular approach for optimising the Two Sum problem due to its low space complexity and excellent time complexity.
  • Focusing to the given constraints (2 <= nums.length <= 10^4, -10^9 <= nums[i] <= 10^9), all approaches ensure the practicality and effectiveness. The assurance of a single valid solution adds clarity to the problem-solving journey.
  • As we say goodbye to traditional techniques, the remaining question invites us to examine algorithms that break away from the O(n^2) time complexity. A call to innovate, finding optimal pathways through the enormous terrain of coding options.
  • In the various algorithms, the option of brute force simplicity, two-pass hash table balance, or one-pass hash table elegance gives variety to problem resolution. As you begin your coding journey, may your solutions be efficient.