702763. Pairs with Difference less than K

Easy

Pairs with Difference less than K

Summary

Given an array of integers, find all pairs that have a difference less than K. This problem is a variation of finding all pairs in an array. The key concept involved is arrays and data structures.

Detailed Explanation

The given array can be sorted first to make it easier to find the pairs with differences less than K. Then, we iterate through the array from both ends (start and end). For each pair of elements at the start and end, check if their difference is less than K. If yes, add this pair to our result.

Here's a step-by-step breakdown:

  • Sort the given array.
  • Initialize two pointers, one at the start and another at the end.
  • Calculate the difference between the elements at the start and end.
  • If the difference is less than K, add this pair to our result.
  • Move the pointer that points to the smaller element towards the other end.
  • Repeat steps 2-5 until the two pointers meet.

Time complexity: O(n log n) due to sorting, where n is the size of the array. Space complexity: O(1), as we are not using any extra space apart from the result.

Here's a sample output for the input [3, 1, 4, 1, 5, 9, 2, 6] and K = 3:

[(1, 2), (1, 3), (1, 4), (2, 3), (4, 5)]

Optimized Solutions

Java

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

public class PairsWithDifferenceLessThanK {
    public static ArrayList<Integer[]> findPairs(int[] arr, int K) {
        Arrays.sort(arr);
        ArrayList<Integer[]> result = new ArrayList<>();
        int i = 0, j = arr.length - 1;
        while (i < j) {
            if (Math.abs(arr[i] - arr[j]) < K) {
                result.add(new Integer[] {arr[i], arr[j]});
                i++;
                j--;
            } else if (arr[i] < arr[j]) {
                i++;
            } else {
                j--;
            }
        }
        return result;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.