703186. Pair the minimum

Easy

Pair the Minimum5535

Summary

The problem "Pair the minimum" is about given an array of integers and a target sum, find all pairs that add up to the target sum. This problem involves working with arrays and data structures, specifically finding a specific pattern within the array.

Detailed Explanation

To solve this problem, we can use a simple two-pointer technique. We first sort the array in ascending order. Then, we initialize two pointers, one at the start of the array (let's call it left) and one at the end of the array (right). We calculate the sum of the elements at these positions.

If the sum is less than the target sum, we move the left pointer to the right to increase the sum. If the sum is greater than the target sum, we move the right pointer to the left to decrease the sum. When the sum equals the target sum, we have found a pair that adds up to the target sum.

We keep track of all these pairs and return them as the result. This solution has a time complexity of O(n log n) due to the sorting step, where n is the size of the array. The space complexity is O(n) for storing the result.

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

  1. Sort the input array in ascending order.
  2. Initialize two pointers, left and right, at the start and end of the array respectively.
  3. Calculate the sum of the elements at the positions pointed by left and right.
  4. If the sum is less than the target sum, move the left pointer to the right to increase the sum.
  5. If the sum is greater than the target sum, move the right pointer to the left to decrease the sum.
  6. When the sum equals the target sum, add the pair to the result and move both pointers towards each other.
  7. Repeat steps 3-6 until the left and right pointers meet or cross over.
  8. Return the list of pairs that add up to the target sum.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PairTheMinimum {
    public static List<List<Integer>> pairTheMinimum(int[] arr, int target) {
        Arrays.sort(arr);
        List<List<Integer>> result = new ArrayList<>();
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int sum = arr[left] + arr[right];
            if (sum == target) {
                result.add(Arrays.asList(arr[left], arr[right]));
                left++;
                right--;
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return result;
    }

DevExCode

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

© 2026 DevExCode. All rights reserved.