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

1 Answer

0 votes
# Finds the maximum distance (absolute index difference) between two numbers in an array.
# 
# @param arr [Array<Integer>] The input array of numbers.
# @param num1 [Integer] The first target number.
# @param num2 [Integer] The second target number.
# @return [Integer, nil] The maximum absolute index difference, or nil if either number is missing.
def max_distance_between_numbers(arr, num1, num2)
  # Variables to track the first and last occurrences of both numbers
  first1 = last1 = nil
  first2 = last2 = nil

  # Single pass through the array: O(N) time complexity, O(1) space complexity
  arr.each_with_index do |current, i|
    if current == num1
      first1 = i if first1.nil? # Record the first time num1 appears
      last1 = i                  # Continuously update the last time num1 appears
    elsif current == num2
      first2 = i if first2.nil? # Record the first time num2 appears
      last2 = i                  # Continuously update the last time num2 appears
    end
  end

  # Edge case: If either number is not present in the array, return nil
  return nil if first1.nil? || first2.nil?

  # 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
  [
    (first1 - last2).abs,
    (last1 - first2).abs
  ].max
end

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

result = max_distance_between_numbers(array, number1, number2)

if result
  puts "The maximum distance between #{number1} and #{number2} is: #{result}"
else
  puts "One or both numbers were not found in the array."
end


# run:
# 
# The maximum distance between 3 and 8 is: 7
#

 



answered Oct 23 by avibootz

Related questions

...