Pair with given Sum

Pair with Given Sum – 2Sum Problem

Given an array of integers nums and an integer target, return the indices i and j such that nums[i] + nums[j] == target and i != j.

You may assume that every input has exactly one pair of indices i and j that satisfy the condition.

Return the answer with the smaller index first.

Pair with given sum - Two Sum

Explanation: nums[0] + nums[1] == 7, so we return [0, 1].

Constraints:

  • 2 <= nums.length <= 1000
  • -10,000,000 <= nums[i] <= 10,000,000
  • -10,000,000 <= target <= 10,000,000

Pair with Given Sum - 2Sum Solution

Recommendation – You should aim for a solution with O(n) time and O(n) space, where n is the size of the input array.

Hints for solving problems

Hint 1 :

A brute force solution would be to check every pair of numbers in the array. This would be an O(n^2) solution. Can you think of a better way? Maybe in terms of mathematical equation?

Hint 2:

Given, We need to find indices i and j such that i != j and nums[i] + nums[j] == target. Can you rearrange the equation and try to fix any index to iterate on?

Hint 3:

Iterate through the array while checking if target – nums[i] exists in the hash map. If not, store the current element with its index in the hash map and continue. This ensures O(1) lookups.

There are mainly 4 approach to solve this problem – 

  1. Brute Force Method
  2. Sorting Method
  3. Hash Map(Two Pass) Method
  4. Hash Map(One Pass) Method

1. Brute Force Method

This method check all possible pairs of numbers in the array to find the ones that add up to the target. Simple but slow for large arrays.

  • Time complexity: O(n^2)
  • Space complexity: O(1)

Code

2. Sorting Method

This method sort the array, then use two pointers (one at the start and one at the end) to find the pair that sums to the target.

  • Time complexity: O(nlogn)
  • Space complexity: O(n)

Code

3. Hash Map(Two Pass) Method

This method first, store all numbers and their indices in a hash map. Then, iterate again to find if the complement (target – current number) exists in the map.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

4. Hash Map(One Pass) Method

This method iterate through the array, check if the complement already exists in the hash map. If not, add the current number with its index to the map.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

More Articles