702810. Find pairs with given relation

Easy

Here is the detailed Markdown blog post for the GeeksforGeeks problem:

Find Pairs with Given Relation

Summary

Find pairs with given relation is an array-based algorithmic problem that involves finding all pairs in an array that satisfy a specific condition. This problem requires a basic understanding of arrays and hash data structures.

Detailed Explanation

The problem statement is not available, so we'll assume it's a general algorithmic problem based on the title and tags. The goal is to find all pairs in an array where the difference between the pair elements satisfies a certain relation (e.g., less than or equal to a given value).

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

  1. First, sort the array in ascending order.
  2. Initialize an empty hash data structure (e.g., a Java HashMap or Python dict) to store the elements and their counts.
  3. Iterate through the sorted array, and for each element:
    • Check if the element is already present in the hash with a count greater than 0.
    • If yes, calculate the difference between the current element and its corresponding value in the hash (if it exists).
    • If the difference satisfies the given relation, add this pair to the result set.
  4. Continue iterating through the array until all elements have been processed.

The time complexity of this algorithm is O(n log n) due to the sorting step, where n is the size of the input array. The space complexity is O(n) for storing the hash data structure and result set.

Here's an ASCII art diagram illustrating the problem:

  +---------------+
  |  Array: [3, 4, 5, 7, 8]  |
  +---------------+

  (Sorted array)
  +---------------+
  |  Array: [3, 4, 4, 5, 5, 5, 7, 8]  |
  +---------------+

  (Hash data structure)
  +---------------+
  |  Hash: { 3: 1, 4: 2, 5: 3, 7: 1, 8: 1 }  |
  +---------------+

  (Pairs with given relation)
  +---------------+
  |  Result set: [(4, 3), (5, 0)]  |
  +---------------+

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.*;

public class FindPairs {
    public static List<List<Integer>> findPairs(int[] arr, int k) {
        List<List<Integer>> result = new ArrayList<>();
        Map<Integer, Integer> countMap = new HashMap<>();

        Arrays.sort(arr);

        for (int i = 0; i < arr.length; i++) {
            if (countMap.containsKey(arr[i] - k)) {
                result.add(Arrays.asList(arr[i], arr[i] - k));
            }
            countMap.put(arr[i], countMap.getOrDefault(arr[i], 0) + 1);
        }

        return result;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.