Finding special kind of elements with in an array in JavaScript

This article explains how to find special pairs of elements in an array where both the value difference and index difference meet specific criteria.

Problem Statement

We need to write a JavaScript function that takes three arguments:

arr --> an array of integers
m --> maximum allowed index difference
n --> maximum allowed value difference

The function should find if there exist two elements (a1 and a2) such that:

  • The absolute difference between a1 and a2 is at most n

  • The absolute difference between the indices of a1 and a2 is at most m

Solution Approach

The algorithm uses a two-pointer technique on a sorted array to efficiently find qualifying pairs:

  1. Create a map of elements with their original indices
  2. Sort by element values to enable two-pointer search
  3. Use left and right pointers to check all potential pairs
  4. Return true if any pair meets both conditions

Example

const arr = [1, 2, 3, 1, 7, 8];

const findSpecialElements = (arr = [], m, n) => {
    const map = arr
        .map((el, ind) => ({ el, ind }))
        .sort((a, b) => a.el - b.el);
    
    let left = 0;
    let right = 1;
    
    while (right  n) {
            left++;
        } else if (indexDiff > m) {
            right++;
        }
        
        if (left === right) {
            right++;
        }
    }
    
    return false;
};

// Test case: m=3 (max index diff), n=0 (max value diff)
console.log(findSpecialElements(arr, 3, 0));
true

How It Works

In this example with arr = [1, 2, 3, 1, 7, 8], m = 3, and n = 0:

  • The algorithm finds elements with value 1 at indices 0 and 3
  • Value difference: |1 - 1| = 0 ? 0 ?
  • Index difference: |3 - 0| = 3 ? 3 ?
  • Both conditions are satisfied, so it returns true

Alternative Simple Approach

For smaller arrays, a brute force approach might be clearer:

const findSpecialElementsSimple = (arr, m, n) => {
    for (let i = 0; i 

true

Time Complexity Comparison

Approach Time Complexity Space Complexity Best For
Two-pointer (optimized) O(n log n) O(n) Large arrays
Brute force O(n²) O(1) Small arrays

Conclusion

The two-pointer approach efficiently finds special element pairs by sorting first, then using pointer movement based on difference comparisons. This algorithm is particularly useful for constraint-based pair finding problems in arrays.

Updated on: 2026-03-15T23:19:00+05:30

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements