(919) 964-9842
(919) 964-9842

Hackerrank in PHP: Counting Valleys

We need to count how many valleys our dear friend Gary is going through. He's a hiker and he wants to count how many valleys will be on his hike. To do this, we've been given an array with his steps, whether he is going down or up (indicated by D or U respectively). We've also been so graciously given the number of steps he is taking as well, so we don't need to do any counting on the array, hooray!

We know we are in a valley if we are below sea level, which is considered zero and is where Gary starts every time.

Let's help out Gary the hiker!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Complete the countingValleys function below.
function countingValleys($n, $s) {
    $valleys = 0;
    $level = 0;
    $isValley = false;

    $path = str_split($s);

    for($i = 0; $i < $n; $i++) {        
        if($path[$i] == 'D') {
            $level--;
        } else if ($path[$i] == 'U') {
            $level++;
        }

        if($level == 0 && $isValley == true) {
            $isValley = false;
            $valleys++;
        } else if($level < 0) {
            $isValley = true;
        }
    }

    return $valleys;
}

What does this all mean? First, we need to two things to count - the sea level and the valleys. Then, we also want a boolean value to check if we are currently in a valley for later (because if we are currently in one, we don't want to double count the value).

Then we need to create an array to parse through, so we use str_split to convert the string into an array. Then, using the total number of steps value, we start a loop. If it's down, the sea level goes down. If it's up, the sea level goes up.

We also have another section that checks if the sea level is under 0, we are in a valley, so that's where our boolean friend comes in handy. We set that to true, and then if we get back to sea level, we reset it and count our valley as one.

It did pass all the tests, but I feel like if Gary did not end up back at sea level at the end of his hike, it wouldn't work because it would never count the last valley. But for this exercise, this code is complete.

Categories: Development

Leave a Reply

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