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

1 Answer

0 votes
import Foundation

/// Finds the maximum distance (absolute index difference) between two numbers in an array.
/// 
/// - Parameters:
///   - arr: The input array of integers.
///   - num1: The first target number.
///   - num2: The second target number.
/// - Returns: The maximum absolute index difference, or nil if either number is missing.
func maxDistanceBetweenNumbers(in arr: [Int], 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
    for (index, current) in arr.enumerated() {
        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 nil
    guard first1 != -1 && first2 != -1 else {
        return nil
    }

    // 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
    let dist1 = abs(first1 - last2)
    let dist2 = abs(last1 - first2)

    return max(dist1, dist2)
}

// --- Example Usage ---
let array = [2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3]
let number1 = 3
let number2 = 8

if let result = maxDistanceBetweenNumbers(in: array, num1: number1, num2: number2) {
    print("The maximum distance between \(number1) and \(number2) is: \(result)")
} else {
    print("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

Related questions

...