Counting Valleys: HackerRank Solution in Python

Shounak Lohokare
1 min readDec 8, 2020

--

Solution in Python 3

Explanation

At first, we will declare two variables level and valleys, and initialize them to 0. We will iterate over the path list using a for loop through a variable called step.

If step equals to ‘U’ we will increment level by 1, which indicates the hiker hiking a level above.

If the level becomes 0 immediately after the hiker climbs a level above then it indicates that the hiker has just crossed a valley.

We interpret above logic in our program in the following way:-

If immediately after climbing a step above the level becomes zero then it indicates that the hiker has crossed a valley and we increment valleys by 1.

If the step is not equal to ‘U’ then it is equal ‘D’ which symbolizes the hiker climbing a level below, for which we will decrease level by 1.

We interpret it in the following way:-

We do not increment the valleys in the case when level becomes 0 immediately after the hiker climbs down a level because such a case symbolizes the hiker crossing a hill.

Note that we do not increment valleys after the step becomes ‘D’ because doing so we will be counting a hill crossed by the hiker. (not a valley)

At the end we return valleys.

return valleys

--

--

Shounak Lohokare
Shounak Lohokare

Written by Shounak Lohokare

pretending to teach is one of the best way to learn.

No responses yet