Counting Valleys

  • + 0 comments

    Hey folks, In this problem, the only confusion part is, if the level is 0 and the step is 'D'(that is down), why we are incrementing the valley count? The answer is we are pretty much looking for the valley. In this case, valley is step down and the sea level is 0. So from the sea level to enters into valley is taken as count one, then because of the problem statement, the hiker definitely needs to reach the sea level after some steps later. Here is the solution in javascript,

    function countingValleys(steps, path) {
        let pathsMap = { D: -1, U: 1 };
        let level = 0;
        let valley = 0;
        path.split("").map(step => {
            if (step === 'D' && level === 0) {
                valley++;
            }
            level = level + pathsMap[step];
        });
        return valley;
    }