How to find the maximum distance between two numbers in a slice with Kotlin

1 Answer

0 votes
import kotlin.math.abs

/**
 * Finds the maximum distance (absolute index difference) between two numbers in an array.
 * 
 * @param arr The input integer array (IntArray).
 * @param num1 The first target number.
 * @param num2 The second target number.
 * @return The maximum absolute index difference, or null if either number is missing.
 */
fun maxDistanceBetweenNumbers(arr: IntArray, num1: Int, num2: Int): Int? {
    // Variables to track the first and last occurrences of both numbers
    var first1 = -1
    var last1 = -1
    var first2 = -1
    var last2 = -1

    // Single pass through the array: O(N) time complexity, O(1) space complexity
    arr.forEachIndexed { index, current ->
        if (current == num1) {
            if (first1 == -1) {
                first1 = index // Record the first time num1 appears
            }
            last1 = index // Continuously update the last time num1 appears
        } else if (current == num2) {
            if (first2 == -1) {
                first2 = index // Record the first time num2 appears
            }
            last2 = index // Continuously update the last time num2 appears
        }
    }

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

    // The maximum distance is always 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
    val dist1 = abs(first1 - last2)
    val dist2 = abs(last1 - first2)

    return maxOf(dist1, dist2)
}

fun main() {
    // --- Example Usage ---
    val array = intArrayOf(2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3)
    val number1 = 3
    val number2 = 8

    val result = maxDistanceBetweenNumbers(array, number1, number2)
    
    if (result != null) {
        println("The maximum distance between $number1 and $number2 is: $result")
    } else {
        println("One or both numbers ($number1, $number2) were not found in the array.")
    }
}


/*
run:

The maximum distance between 3 and 8 is: 7

*/

 



answered Oct 23 by avibootz
...