Counting Valleys: HackerRank Solution in Python
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 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:-
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