Created
May 10, 2022 07:34
-
-
Save ahangarha/89614ed5f6cece244dbe838362a9173c to your computer and use it in GitHub Desktop.
Minimum Distances - Ruby - HackerRank
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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