Counting Valleys

Sort by

recency

|

176 Discussions

|

  • + 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;
    }
    
  • + 0 comments

    A rust solution:

    fn countingValleys(steps: i32, path: &str) -> i32 {
        let (_, valley) = path.bytes()
            .fold((0, 0), |mut acc, step| {
                if acc.0 == -1 && step == b'U' {
                    acc.1 += 1;
                }
                
                if step == b'U' { 
                    acc.0 += 1
                } else if step == b'D' { 
                    acc.0 -= 1;
                }
                
                acc
            });
        valley
    }
    
  • + 0 comments
    func countingValleys(steps int32, path string) int32 {
        stepsCount := 0
        valleys := 0
        seaLevel := 0
        for _, char := range path {
            if char == 'U' {
                stepsCount++
            } else if char == 'D' {
                if stepsCount == seaLevel {
                    valleys++
                }
                stepsCount--
            }
        }
    
        return int32(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;
    }
    
  • + 1 comment

    def countingValleys(steps, path):

    n = 0
    p = 0
    for i in path:
        if i == 'D':
            n -= 1
        else:
            n += 1
            if n == 0:
                p += 1
    return p