876221. All Pairs With Given Sum

Easy

Here is the Markdown blog post for the "All Pairs With Given Sum" problem:

All Pairs With Given Sum

Summary

Find all pairs in a given array that sum up to a target value. This problem involves arrays and hash techniques, making it an easy yet interesting challenge.

Detailed Explanation

To solve this problem, we can use a simple approach involving two pointers technique. The idea is to iterate through the array with two pointers, one starting from the beginning of the array (let's call it i) and the other starting from the end of the array (j). At each step, calculate the sum of the elements at indices i and j. If the sum equals the target value, add the pair (array[i], array[j]) to our result set. Move the pointers accordingly based on whether the sum is less than, greater than, or equal to the target.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty list result to store the pairs that sum up to the target value.
  2. Iterate through the array with two pointers, i starting from 0 and j starting from the end of the array (size - 1).
  3. Calculate the sum of elements at indices i and j.
  4. If the sum equals the target value, add the pair (array[i], array[j]) to the result list.
  5. Move the pointers accordingly:
    • If the sum is less than the target, increment i to increase the sum.
    • If the sum is greater than the target, decrement j to decrease the sum.
  6. Repeat steps 2-5 until i and j meet in the middle (when i == j).
  7. Return the result list containing all pairs that sum up to the target value.

Time complexity: O(n), where n is the size of the array, since we only iterate through the array once. Space complexity: O(n), as we store the result in a list of length proportional to the size of the array.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

public class Main {
    public static List<int[]> findPairs(int[] arr, int target) {
        List<int[]> result = new ArrayList<>();
        int i = 0;
        int j = arr.length - 1;

        while (i < j) {
            int sum = arr[i] + arr[j];
            if (sum == target) {
                result.add(new int[]{arr[i], arr[j]});
                i++;
                j--;
            } else if (sum < target) {
                i++;
            } else {
                j--;
            }
        }

        return result;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int target = 7;
        List<int[]> result = findPairs(arr, target);
        System.out.println(result); // Output: [[1, 6], [2, 5]]
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.