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

1 Answer

0 votes
/// Finds the maximum distance (absolute index difference) between two numbers in a slice.
///
/// # Arguments
/// * `slice` - A slice of items that implement `Eq`.
/// * `num1` - The first target number.
/// * `num2` - The second target number.
///
/// # Returns
/// * `Option<usize>` - `Some(distance)` if both numbers exist, or `None` if either is missing.
pub fn max_distance_between_numbers<T: Eq>(slice: &[T], num1: &T, num2: &T) -> Option<usize> {
    // Track the first and last occurrences of both numbers using Option<usize>
    let mut first1: Option<usize> = None;
    let mut last1: Option<usize> = None;
    let mut first2: Option<usize> = None;
    let mut last2: Option<usize> = None;

    // Single pass through the slice: O(N) time complexity, O(1) space complexity
    for (i, item) in slice.iter().enumerate() {
        if item == num1 {
            if first1.is_none() {
                first1 = Some(i); // Record the first time num1 appears
            }
            last1 = Some(i); // Continuously update the last time num1 appears
        } else if item == num2 {
            if first2.is_none() {
                first2 = Some(i); // Record the first time num2 appears
            }
            last2 = Some(i); // Continuously update the last time num2 appears
        }
    }

    // Edge case: Return None if either number was not found in the slice
    let (f1, l1, f2, l2) = (first1?, last1?, first2?, last2?);

    // 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 = l2.abs_diff(f1);
    let dist2 = l1.abs_diff(f2);

    Some(dist1.max(dist2))
}

fn main() {
    // --- Example Usage ---
    let array = [2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3];
    let number1 = 3;
    let number2 = 8;

    match max_distance_between_numbers(&array, &number1, &number2) {
        Some(distance) => {
            println!(
                "The maximum distance between {} and {} is: {}",
                number1, number2, distance
            );
        }
        None => {
            println!(
                "One or both numbers ({}, {}) were not found in the array.",
                number1, number2
            );
        }
    }
}


/*
run:

The maximum distance between 3 and 8 is: 7

*/

 



answered Oct 23 by avibootz
...