Counting Valleys – HackerRank Challenge

Share on facebook
Share on google
Share on twitter
Share on linkedin

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 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;
}