HackerRank: Counting Valleys Challenge

This week I continued down the HackerRank interview preparation kit. The next challenge to tackle is Counting Valleys. This function will take in a string made up of a combination of “U” and “D” representing up and down, respectively. This string represents a hike that somebody takes on a trail, and the function will return an integer that represents how many times the hiker exits a valley that they had previously entered. For example, if the string given to the function is “DDUUUUDD”, then the returned value will be 1, since the path drops below the starting level and rises back out one time. You can see a picture of this logic below.

Visualization of the Valley Problem

The way I decided to approach this problem starts by setting two variables, currentLevel and valleysExited set to zero. Since the beginning of the string is “sea-level” or technically 0, the currentLevel variable will keep track of the change from 0 as the function runs. The valleysExited variable keeps track of the amount of times a valley is exited (kind of self explanatory).

Variables Created for Solution

To find the solution for this function, I knew I needed to iterate through the passed in path string. To figure out what the current level of the path is, I knew I had to subtract one from the currentLevel variable when the value in the string was “D” and add one to the variable when the value was “U”. This keeps track of the level above or below the starting level, but this doesn’t get an answer that will give me a passing function.

Beginning the Loop

The final step of the loop, and the final step for a function that passes all test cases, is to create a second if statement inside the loop. The first thing this statement will do is check what the current level of the path is. To exit a valley, the first thing that needs to be true is that the current level is zero, or the beginning level. The second thing that needs to be true is the current letter in the string being isolated in the loop needs to be “U”. If the current letter was “D”, then the path would be going back down, which means a valley wouldn’t be exited. If those two stipulations are met, then the valleysExited variable will be increased by one. Once this loop finishes, there’s a completed value that can be returned at the end of the function to give a solution that passes every test case!

Finished Function