iOS Interview - Leetcode 232. Implement Queue using Stacks

May 15, 20241 min read#swift, #interview, #leetcode

Leetcode: 232. Implement Queue using Stacks

  • Primary idea: Use an array as stack
  • Time Complexity: O(n)
  • Space Complexity: O(n)
class MyQueue {
    var stack = [Int]()

    init() {

    }

    func push(_ x: Int) {
        stack.append(x)
    }

    func pop() -> Int {
        stack.removeFirst()
    }

    func peek() -> Int {
        return stack.first ?? 0
    }

    func empty() -> Bool {
        stack.isEmpty
    }
}

let obj = MyQueue()
obj.push(1)
let ret_2: Int = obj.pop() // 1
let ret_3: Int = obj.peek() // 0
let ret_4: Bool = obj.empty() // true
Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024