Counting Valleys

Absolutely one of my favorite problems. The counting valleys problem is about a hiker who records his steps. The output must be to count the number of valleys the hiker walked through. Two things we had to keep in mind were:

  • mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
  • valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.

from: https://www.hackerrank.com/challenges/counting-valleys/problem

Given an input steps (int) and a string path, return the numbers of valleys (int) traversed.

Sample Input:

8
UDDDUDUU

Sample Output:

1
The input can be illustrated above. First the hiker went up a hill, then down and entered into a valley (2 consecutive D’s). Then by the end, he exited the valley (2 consecutive U’s). Hence, he only traversed through 1 valley.

Here’s my solution:

def countingValleys(steps, path):
    # Write your code here
    elevation = 0
    valleys = 0
    for step in path:
        if step == 'D':
            elevation -= 1
        elif step == 'U':
            elevation += 1
        if elevation == 0 and step == 'U':
            valleys += 1
            
    return valleys

Leave a comment

Your email address will not be published. Required fields are marked *