Largest index difference with an increasing value in JavaScript

We need to write a JavaScript function that finds the largest difference between two indices j - i where arr[i] ? arr[j]. This means we're looking for the maximum distance between two positions where the value at the later position is greater than or equal to the value at the earlier position.

Problem Statement

Given an array of numbers, find the maximum value of (j - i) such that arr[i] ? arr[j] and i

Example

Let's implement a solution that checks all possible pairs:

const arr = [1, 2, 3, 4];

const findLargestDifference = (arr = []) => {
    const { length: len } = arr;
    let res = 0;
    
    for(let i = 0; i < len; i++){
        for(let j = i + 1; j < len; j++){
            if(arr[i] <= arr[j] && (j - i) > res){
                res = j - i;
            }
        }
    }
    return res;
};

console.log(findLargestDifference(arr));
3

How It Works

The algorithm uses nested loops to compare every pair of elements where i

  • Compare arr[0]=1 with arr[1]=2, arr[2]=3, arr[3]=4 (all satisfy 1 ? value)
  • The maximum difference is between indices 0 and 3: (3 - 0) = 3

Optimized Approach

We can optimize this using a more efficient approach that reduces time complexity:

const findLargestDifferenceOptimized = (arr = []) => {
    const len = arr.length;
    if (len < 2) return 0;
    
    // Create arrays to store min from left and max from right
    const leftMin = new Array(len);
    const rightMax = new Array(len);
    
    // Fill leftMin array
    leftMin[0] = 0;
    for (let i = 1; i < len; i++) {
        leftMin[i] = (arr[i] < arr[leftMin[i-1]]) ? i : leftMin[i-1];
    }
    
    // Fill rightMax array
    rightMax[len-1] = len-1;
    for (let j = len-2; j >= 0; j--) {
        rightMax[j] = (arr[j] > arr[rightMax[j+1]]) ? j : rightMax[j+1];
    }
    
    // Find maximum j - i
    let i = 0, j = 0, maxDiff = 0;
    while (i < len && j < len) {
        if (arr[leftMin[i]] <= arr[rightMax[j]]) {
            maxDiff = Math.max(maxDiff, rightMax[j] - leftMin[i]);
            j++;
        } else {
            i++;
        }
    }
    
    return maxDiff;
};

const testArr = [34, 8, 10, 3, 2, 80, 30, 33, 1];
console.log("Array:", testArr);
console.log("Largest difference:", findLargestDifferenceOptimized(testArr));
Array: [34, 8, 10, 3, 2, 80, 30, 33, 1]
Largest difference: 6

Comparison

Approach Time Complexity Space Complexity Best For
Brute Force O(n²) O(1) Small arrays
Optimized O(n) O(n) Large arrays

Conclusion

The brute force approach is simple and works well for small arrays, while the optimized solution provides better performance for larger datasets. Choose the approach based on your array size and performance requirements.

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

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements