Index difference of tuples in JavaScript

Problem

We are required to write a JavaScript function that takes in an array of integers, arr, as the first and the only argument.

Suppose two indices, i and j in the array which satisfy the following conditions ?

  • i < j, and

  • arr[i] <= arr[j]

Out of all such index tuples (i, j), our function should return the difference j - i, where it is the maximum.

For example, if the input to the function is ?

const arr = [6, 0, 8, 2, 1, 5];

Then the output should be ?

const output = 4;

Output Explanation

The maximum difference is achieved at (i, j) = (1, 5): arr[1] = 0 and arr[5] = 5.

Approach Using Stack

The solution uses a stack-based approach to efficiently find the maximum difference. First, we build a decreasing stack of indices, then traverse from right to left to find valid pairs.

const arr = [6, 0, 8, 2, 1, 5];
const maximumDifference = (arr = []) => {
    let max = 0;
    const stack = [0];
    
    // Build decreasing stack
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] < arr[stack[stack.length - 1]]) {
            stack.push(i);
        }
    }
    
    // Find maximum difference
    for (let i = arr.length - 1; i >= 0; i--) {
        while (stack.length > 0 && arr[i] >= arr[stack[stack.length - 1]]) {
            max = Math.max(max, i - stack.pop());
        }
    }
    return max;
};

console.log(maximumDifference(arr));
4

How It Works

The algorithm works in two phases:

  1. Build Stack: Create a stack of indices where each element is smaller than the previous one
  2. Find Maximum: Traverse from right to left, popping from stack when we find valid pairs (arr[i] >= arr[stack_top])

Alternative Brute Force Approach

For better understanding, here's a simpler O(n²) solution:

const arr = [6, 0, 8, 2, 1, 5];
const maximumDifferenceBrute = (arr = []) => {
    let max = 0;
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (arr[i] <= arr[j]) {
                max = Math.max(max, j - i);
            }
        }
    }
    return max;
};

console.log(maximumDifferenceBrute(arr));
4

Comparison

Approach Time Complexity Space Complexity Best For
Stack-based O(n) O(n) Large arrays
Brute Force O(n²) O(1) Small arrays, learning

Conclusion

The stack-based approach efficiently finds the maximum index difference in linear time. It's optimal for finding tuple differences where the left element is smaller than or equal to the right element.

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

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements