cook your code here
#ruby code
tc = gets.chomp.to_i
tc.times{
max = 1
length = gets.chomp.to_i
string = gets.chomp
hash = {}
string.each_char.with_index { |char, i|
if hash[char]
max = [length-i ,max].max
else
hash[char]=1
end
# p hash,max
}
p max
}
Can someone explain why this code can’t pass any test case?
Can you explain your logic ?
max = 0
hash = {}
#creating new hash
for each_character_with_index in string
#let the string be “abcd”, this loop runs for (a,0) (b,1) (c,2) (d,3)
if hash[character] == 1
#checking whether this character already occurred in the string
max = maximum of max and (string_length - current_index)
else
hash[character]=1
#endif
#endfor
print max
please let me know if you can’t get this.
Your logic is correct. you need to find the shortest distance between any two repeating letters. But you should find a better way to find any repeated letter. This way you might get TLE due to o(n) complexity
Thanks for the help.
But not even a single test case is passed. For every case the result is WrongAnswer only.