Skip to content

Instantly share code, notes, and snippets.

@renatamarques97
Last active December 6, 2020 21:56
Show Gist options
  • Select an option

  • Save renatamarques97/5874177641a9847d82f09ddebf6281fe to your computer and use it in GitHub Desktop.

Select an option

Save renatamarques97/5874177641a9847d82f09ddebf6281fe to your computer and use it in GitHub Desktop.
# https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup
# samples
path = "UDDDUDUU"
path = "UUUUUUUU"
path = "DDDDDDDD"
path = "UUUDDD"
path = "UUUUDD"
# ruby 2.7+
def validatingValleys(path)
path_splitted = path.split("")
values = path_splitted.tally.values
return 1 if path_splitted.count.even? && values.count > 1 && values.uniq.size == 1
0
end
# past versions
def validatingValleys(path)
path_splitted = path.split("")
values = path_splitted.group_by(&:itself).transform_values{|v| v.size}.values
return 1 if path_splitted.count.even? && values.count > 1 && values.uniq.size == 1
0
end
def countingValleys(steps, path)
position = 0
valleys = 0
path.each_char do |step|
old_position = position
position += 1 if step == "U"
position -= 1 if step == "D"
valleys += 1 if position.zero? && old_position.negative?
end
valleys
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment