Counting Valleys

  • + 0 comments

    My TypeScript solution:

    function countingValleys(steps: number, path: string): number {
        let currentDepth = 0;
        let valleys = 0;
        
        for (let i = 0; i < steps; i++) {     
            if (path[i] === "D" && currentDepth === 0) valleys ++;  
            currentDepth += path[i] === "U" ? 1 : -1;
        }
        
        return valleys;
    }