How to find the maximum distance between two numbers in an array with TypeScript

1 Answer

0 votes
/**
 * Finds the maximum distance (absolute index difference) between two numbers in an array.
 * 
 * @param arr - The input array of numbers.
 * @param num1 - The first target number.
 * @param num2 - The second target number.
 * @returns The maximum absolute index difference, or null if either number is missing.
 */
function maxDistanceBetweenNumbers(arr: number[], num1: number, num2: number): number | null {
    // Variables to track the first and last occurrences of both numbers
    let first1: number = -1;
    let last1: number = -1;
    let first2: number = -1;
    let last2: number = -1;

    // Single pass through the array: O(N) time complexity, O(1) space complexity
    for (let i: number = 0; i < arr.length; i++) {
        const current: number = arr[i];

        if (current === num1) {
            if (first1 === -1) {
                first1 = i; // Record the first time num1 appears
            }
            last1 = i; // Continuously update the last time num1 appears
        } 
        else if (current === num2) {
            if (first2 === -1) {
                first2 = i; // Record the first time num2 appears
            }
            last2 = i; // Continuously update the last time num2 appears
        }
    }

    // Edge case: If either number is not present in the array, distance cannot be calculated
    if (first1 === -1 || first2 === -1) {
        return null;
    }

    // The maximum distance will always be between the outermost boundaries of the two sets:
    // 1. Distance between the first occurrence of num1 and the last occurrence of num2
    // 2. Distance between the last occurrence of num1 and the first occurrence of num2
    return Math.max(
        Math.abs(first1 - last2),
        Math.abs(last1 - first2)
    );
}

// --- Example Usage ---
const array: number[] = [2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3];
const number1: number = 3;
const number2: number = 8;

const result: number | null = maxDistanceBetweenNumbers(array, number1, number2);
console.log(`The maximum distance between ${number1} and ${number2} is: ${result}`);


/*
run:

The maximum distance between 3 and 8 is: 7

*/

 



answered Oct 22 by avibootz
...