Skip to content

Instantly share code, notes, and snippets.

@ahangarha
Created May 10, 2022 07:34
Show Gist options
  • Save ahangarha/89614ed5f6cece244dbe838362a9173c to your computer and use it in GitHub Desktop.
Save ahangarha/89614ed5f6cece244dbe838362a9173c to your computer and use it in GitHub Desktop.
Minimum Distances - Ruby - HackerRank
#!/bin/ruby
require 'json'
require 'stringio'
#
# Complete the 'minimumDistances' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY a as parameter.
#
def minimumDistances(arr)
# Write your code here
min_distance = -1
pairs = {}
#find pairs - O(n)
arr.each_with_index do |a, i|
if pairs[a]
current_distance = i - pairs[a][0]
min_distance = min_distance == -1 ? current_distance : [min_distance, current_distance].min
pairs[a] << i
else
pairs[a] = [i]
end
end
min_distance
end
fptr = File.open(ENV['OUTPUT_PATH'], 'w')
n = gets.strip.to_i
a = gets.rstrip.split.map(&:to_i)
result = minimumDistances a
fptr.write result
fptr.write "\n"
fptr.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment