Check out example codes for "the hiker first enters a valley 2 units deep". It will help you in understanding the concepts better.

Code Example 1

function countingValleys(n, s) {    let level = 0;    let result = 0;    [...s].reduce((target, step) => {        step.match(/u/i) ? level++ : level--;        (!target && level >= 0) && (result++);        target = !!(level >= 0);        return target;    }, true);    return result;}

Learn ReactJs, React Native from akashmittal.com