Hackerrank Solution: Counting Valleys

Original Problem

Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly \(n\) steps. For every step he took, he noted if it was an uphill, \(U\), or a downhill, \(D\) step. Gary's hikes start and end at sea level and each step up or down represents a unit change in altitude. We define the following terms:

Given Gary's sequence of up and down steps during his last hike, find and print the number of valleys he walked through.

For example, if Gary's path is \(s=[DDUUUUDD]\), he first enters a valley \(2\) units deep. Then he climbs out an up onto a mountain \(2\) units high. Finally, he returns to sea level and ends his hike.

Function Description

Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed.

countingValleys has the following parameters:

Input Format

The first line contains an integer \(n\), the number of steps in Gary's hike.The second line contains a single string \(s\), of \(n\) characters that describe his path.

Solution

The trick for this problem is that we check if the previous step was still above sea-level and passes sea level with the current step. After that the implementation is just

def countingValleys(n, s):
    h = 0
    c = 0
    for p in s:
        a = (p == 'U') - (p == 'D')
        if a + h < 0 and h >= 0:
            c+= 1
        h+= a
    return c

« Back to problem overview