Last active
December 6, 2020 21:56
-
-
Save renatamarques97/5874177641a9847d82f09ddebf6281fe to your computer and use it in GitHub Desktop.
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
| # 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