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:
- A 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.
- A 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

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