Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I solve this problem in Swift. I'm not sure if using an array was the right way to approach it since the problem was on stacks. Any feedback on my code is appreciated:

You have an empty sequence, and you will be given N queries. Each query is one of these three types:

1 x -Push the element x into the stack.

2 -Delete the element present at the top of the stack.

3 -Print the maximum element in the stack.

import Foundation

/// Returns an integer read from one line of standard input.
func readInteger() -> Int {
    guard let line = readLine() else {
        fatalError("Unexpected end of input")
    }
    guard let i = Int(line) else {
        fatalError("Invalid integer in input")
    }
    return i
}

// Returns an array of integers read from one line of standard input.
func readIntegers() -> [Int] {
    guard let line = readLine() else {
        fatalError("Unexpected end of input")
    }
    return line.componentsSeparatedByString(" ").map{ Int($0)! }
}

// returns maximum element in stack
func maxElement() {
    let queries = readInteger()
    var stack = [Int]()

    // loops through each query
    for _ in 0..<queries {
        let input = readIntegers()
        let type = input[0]
        switch type {
        case 1:
            // 2nd input only given when type is 1
            let element = input[1]
            stack.append(element)
        case 2:
            // deletes element at top of the stack
            // stack is LIFO
            stack.removeLast()
        case 3:
            if let maxElement = stack.maxElement() {
                print(maxElement)
            }
        default:
            fatalError("Unknown input type")
        }
    }
}

maxElement()
share|improve this question
    
If you kept a second, parallel stack, you could use it to track the current maximum element, and never have to do a search when asked for that value. Equally, you could push tuples onto the stack and always know the maximum element that way – Feldur Aug 1 at 15:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.