703316. Number of pairs

Medium

Here is a detailed Markdown blog post for the problem:

Number of Pairs3422

Summary

This problem involves counting the number of pairs in an array where each pair consists of two distinct elements that sum up to a given target value. The tags include "Arrays", "Sorting", and "Data Structures" which suggests that we need to find all possible pairs in an array that satisfy certain conditions.

Detailed Explanation

The problem is asking us to count the number of pairs in an array where each pair consists of two distinct elements that sum up to a given target value. For example, if the array is [1, 2, 3, 4, 5] and the target value is 7, then the pairs are (2, 5) and (3, 4). We need to find all such pairs in the array.

One approach to solve this problem is by sorting the array first. This is because we can use two pointers technique to find all possible pairs that sum up to the target value. Here's how it works:

  1. Sort the array in ascending order.
  2. Initialize two pointers, left and right, to the start and end of the array respectively.
  3. Calculate the sum of the elements at the left and right indices.
  4. If the sum is equal to the target value, then we found a pair (arr[left], arr[right]). Increment both pointers and continue until the sum is no longer equal to the target value.
  5. Repeat steps 3-4 until the left pointer meets the right pointer.

This algorithm 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(1) as we only need a constant amount of space to store the pointers and the sum.

Here's an ASCII art diagram to illustrate the two-pointer technique:

  +--------+       +--------+
  |  arr[0]  |       |  arr[n-1]  |
  +--------+       +--------+
           |               |
           |  left          |
           v               |
  +--------+       +--------+
  |  arr[i]   |       |  arr[j]    |
  +--------+       +--------+
           |               |
           |  right         |
           v               |

Optimized Solutions

Java

View on GeeksforGeeks
public int countPairs(int[] arr, int target) {
    Arrays.sort(arr);
    int count = 0;
    int left = 0;
    int right = arr.length - 1;
    while (left < right) {
        int sum = arr[left] + arr[right];
        if (sum == target) {
            count++;
            left++;
            right--;
        } else if (sum < target) {
            left++;
        } else {
            right--;
        }
    }
    return count;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.