Tutorialspoint
Problem
Solution
Submissions

Target Sum

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a Python program to find all unique pairs of numbers in an array that sum up to a given target value. Each pair should be returned as an array of two numbers, and the result should not contain duplicate pairs.

Example 1
  • Input: nums = [1, 2, 3, 4, 5, 6], target = 7
  • Output: [[1, 6], [2, 5], [3, 4]]
  • Explanation:
    • We need to find pairs that sum to 7.
    • 1 + 6 = 7, so [1, 6] is a valid pair.
    • 2 + 5 = 7, so [2, 5] is a valid pair.
    • 3 + 4 = 7, so [3, 4] is a valid pair.
    • Therefore, we have three pairs that sum to 7.
Example 2
  • Input: nums = [1, 1, 2, 2, 3, 3], target = 4
  • Output: [[1, 3], [2, 2]]
  • Explanation:
    • We need to find pairs that sum to 4.
    • 1 + 3 = 4, so [1, 3] is a valid pair.
    • 2 + 2 = 4, so [2, 2] is a valid pair.
    • We avoid duplicate pairs, so only unique combinations are returned.
Constraints
  • 2 ≤ nums.length ≤ 1000
  • -10^9 ≤ nums[i] ≤ 10^9
  • -10^9 ≤ target ≤ 10^9
  • Return pairs in ascending order
  • Each pair should be in ascending order [smaller, larger]
  • Time Complexity: O(n log n)
  • Space Complexity: O(n)
ArraysWiproPwC
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Sort the array first to make it easier to find pairs and avoid duplicates
  • Use two pointers approach - one at the beginning and one at the end
  • If the sum of elements at both pointers equals target, add to result
  • If sum is less than target, move left pointer right
  • If sum is greater than target, move right pointer left
  • Skip duplicate elements to avoid duplicate pairs

Steps to solve by this approach:

 Step 1: Sort the input array in ascending order to enable two-pointer technique.
 Step 2: Initialize left pointer at start (0) and right pointer at end (length-1).
 Step 3: Calculate sum of elements at left and right pointers.
 Step 4: If sum equals target, add pair to result and move both pointers.
 Step 5: If sum is less than target, move left pointer right to increase sum.
 Step 6: If sum is greater than target, move right pointer left to decrease sum.
 Step 7: Skip duplicate elements to avoid adding duplicate pairs to result.
 Step 8: Continue until left pointer meets or crosses right pointer.

Submitted Code :