Distance between 2 duplicate numbers in an array JavaScript

We are required to write a JavaScript function that takes in an array of numbers that contains at least one duplicate pair of numbers.

Our function should return the distance between all the duplicate pairs of numbers that exist in the array. The distance is calculated as the minimum difference between indices where duplicate numbers appear.

Example

Let's work with an array containing duplicates and find the minimum distance between each duplicate pair:

const arr = [2, 3, 4, 2, 5, 4, 1, 3];
const findDistance = arr => {
    var map = {}, res = {};
    arr.forEach((el, ind) => {
        map[el] = map[el] || [];
        map[el].push(ind);
    });
    Object.keys(map).forEach(el => {
        if (map[el].length > 1) {
            res[el] = Math.min.apply(null, map[el].reduce((acc, val, ind, arr) => {
                ind && acc.push(val - arr[ind - 1]);
                return acc;
            }, []));
        };
    });
    return res;
}
console.log(findDistance(arr));
{ '2': 3, '3': 6, '4': 3 }

How It Works

The algorithm follows these steps:

  1. Map Creation: Store all indices for each number in a map object
  2. Distance Calculation: For numbers with multiple occurrences, calculate distances between consecutive indices
  3. Minimum Distance: Return the smallest distance for each duplicate number

Step-by-Step Breakdown

Let's trace through the example array [2, 3, 4, 2, 5, 4, 1, 3]:

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

// Step 1: Map indices for each number
console.log("Index mapping:");
const map = {};
arr.forEach((el, ind) => {
    map[el] = map[el] || [];
    map[el].push(ind);
});
console.log(map);

// Step 2: Calculate distances for duplicates
console.log("\nDistance calculations:");
console.log("Number 2 appears at indices [0, 3] - distance: 3");
console.log("Number 3 appears at indices [1, 7] - distance: 6"); 
console.log("Number 4 appears at indices [2, 5] - distance: 3");
Index mapping:
{ '1': [ 6 ], '2': [ 0, 3 ], '3': [ 1, 7 ], '4': [ 2, 5 ], '5': [ 4 ] }

Distance calculations:
Number 2 appears at indices [0, 3] - distance: 3
Number 3 appears at indices [1, 7] - distance: 6
Number 4 appears at indices [2, 5] - distance: 3

Simplified Version

Here's a more readable version of the same algorithm:

function findDistanceSimple(arr) {
    const indexMap = {};
    const distances = {};
    
    // Store all indices for each number
    arr.forEach((num, index) => {
        if (!indexMap[num]) {
            indexMap[num] = [];
        }
        indexMap[num].push(index);
    });
    
    // Calculate minimum distance for duplicates
    for (const num in indexMap) {
        const indices = indexMap[num];
        if (indices.length > 1) {
            let minDistance = Infinity;
            for (let i = 1; i 

{ '1': 2, '2': 3, '4': 3 }

Conclusion

This algorithm efficiently finds the minimum distance between duplicate numbers by mapping indices and calculating consecutive differences. It handles multiple duplicates and returns only numbers that appear more than once in the array.

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

203 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements