Counting Valleys

Sort by

recency

|

178 Discussions

|

  • + 0 comments

    This is a classic stack solution. My answer in Kotlin:

    fun countingValleys(steps: Int, path: String): Int {
        var valleyCount = 0
        var hikeStack : Stack<Char> = Stack()
        path.forEach { stepType ->
            when{
                (hikeStack.isEmpty() || hikeStack.peek() == 'U') && stepType == 'U' -> hikeStack.add('U')
                hikeStack.isEmpty() && stepType == 'D' -> { 
                    valleyCount += 1
                    hikeStack.add('D') 
                } 
                hikeStack.peek() == 'D' && stepType == 'D' -> hikeStack.add('D')
                else -> hikeStack.pop()
            }
        }
        return valleyCount
    }
    

    The catch is: when we have an empty stack we are in sea level, then if we receive a 'D', we enter a Valley, and will stay inside a valley until the stack is empty again. Same thing for a mountain.

  • + 0 comments
    def countingValleys(steps, path):
        valleys = 0
        height = 0
        step = 0   
         
        for i in path:
            print(height)
            if i == 'U':
                step = 1
            elif i == 'D':
                step = -1
            
            if height == 0 and step == -1:
                valleys += 1
            
            height += step
    
        return 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;
    }
    
  • + 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)
    
    }