Counting Valleys

  • + 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.