TzookB

Counting Valleys – HackerRank Challenge

Wed May 15 2019

The Problem: We have a traveler that travelers that counts his steps Up and Downs. He now wants to know how many valleys he passed through. Valley is one or more step below sea level and back to sea level.

My solution on Github [HackerRank challenge][1] The Code:
function countingValleys(n, s) {
    //dont care about "n"
    let level = 0;
    let valleys = 0;
    let isNewVally = false;

    s.split('').map(step => {
        level = step === 'U' ? level + 1 : level -1;
        if (level === -1 && !isNewVally) {
            isNewVally = true;
        }
        if (level === 0 && isNewVally) {
            isNewVally = false;
            valleys++;
        }
    })
    return valleys;
}