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

1 Answer

0 votes
object DistanceFinder {

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

    // Single pass through the array: O(N) time complexity, O(1) space complexity
    for ((current, i) <- arr.zipWithIndex) {
      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, return None
    if (first1 == -1 || first2 == -1) {
      None
    } else {
      // 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 = math.abs(first1 - last2)
      val dist2 = math.abs(last1 - first2)

      Some(math.max(dist1, dist2))
    }
  }

  def main(args: Array[String]): Unit = {
    // --- Example Usage ---
    val array = Array(2, 3, 7, 3, 3, 4, 8, 8, 8, 11, 9, 1, 3)
    val number1 = 3
    val number2 = 8

    maxDistanceBetweenNumbers(array, number1, number2) match {
      case Some(distance) =>
        println(s"The maximum distance between $number1 and $number2 is: $distance")
      case None =>
        println(s"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

...