Problem overview
A stack is a pile where you only touch the top. The last value you put in is the first one you take out, which is called LIFO, last in, first out. Think of a pile of plates: you add to the top and take from the top.
The lesson asks for a class MyStack that stores whole numbers in a private var data = [Int]() array and offers four operations:
push(_ value: Int)puts a value on top and returns nothing.pop() -> Intremoves the top value and returns it.peek() -> Intreturns the top value but leaves it on the stack.size() -> Intreturns how many values are on the stack.
The driver pushes 10, 20 and 30, then peeks, pops everything, and finally pushes 7 onto the emptied stack. The output is:
Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1
Pops come out as 30, 20, 10, the reverse of the order they went in. After the last pop the size is 0, and the stack keeps working: the push of 7 gives a top of 7 and a size of 1.
Approach: the end of the array is the top
The array does the storage, and the only decision is which end of it is the top of the stack. Choose the end. Adding and removing at the end of a Swift array is cheap, and the most recently pushed value is always the last element. If the top were the front, every push and pop would have to shift all the other elements.
With that choice, each operation is a single array call: append for push, removeLast() for pop, last for peek and count for size.
Step by step
- Declare the class and write its closing brace immediately. The driver's
MyStack()builds an object from it. - Add the storage:
private var data = [Int](). It isvarbecause the array changes, andprivatebecause outside code should go through the four methods and never touch the array. - Start
push. Swift normally makes callers write a parameter's name, but the underscore beforevalueturns that off, so the driver can writestack.push(10). - Append the value to the end of
data. - Start
pop, which returns anInt. - Return
data.removeLast(). That one call removes the last element and hands it back, so the stack shrinks and the caller gets the value. - Start
peek, also returning anInt. - Return
data.last!. The propertylastis an optional, because an empty array has no last element. The!unwraps it, asserting that a value is there. - Start
sizewith anIntresult. - Return
data.count, one array element per stacked value.
The solution in Swift
class MyStack {
private var data = [Int]()
func push(_ value: Int) {
data.append(value)
}
func pop() -> Int {
return data.removeLast()
}
func peek() -> Int {
return data.last!
}
func size() -> Int {
return data.count
}
}
class Solution {
func mainFunction() {
let stack = MyStack()
stack.push(10)
stack.push(20)
stack.push(30)
print("Top: \(stack.peek())")
print("Size: \(stack.size())")
print("Pop: \(stack.pop())")
print("Size: \(stack.size())")
print("Pop: \(stack.pop())")
print("Pop: \(stack.pop())")
print("Empty size: \(stack.size())")
stack.push(7)
print("Top: \(stack.peek())")
print("Size: \(stack.size())")
}
}
Details worth knowing
popversuspeek. Both give back the top value, butremoveLast()changes the array andlastonly reads it. Callingpeek()twice gives the same answer and leaves the size alone. For a stack holding 1 and 2,peek()twice and thensize()prints2 2 2.- Why
lastis optional. Swift makes you handle the case of an empty array. The lesson's!says "I know there is a value". It is safe here because the tests never peek at an empty stack. - Why
removeLast()is not optional. The array methodpopLast()returns an optional, butremoveLast()returns the element itself and requires the array not to be empty. - Private storage. Because
datais private, nobody can reorder or remove from the middle of the pile, which would break the rule that only the top is accessible.
Complexity
Every operation takes constant time. append is amortized O(1): occasionally the array has to grow, but averaged over many pushes the cost per push is constant. removeLast(), last and count are all O(1). The stack uses O(n) space for the n values it currently holds.
Edge cases and common mistakes
- Popping or peeking an empty stack. The tests never do it, but in Swift both
removeLast()andlast!on an empty array stop the program with a crash rather than returning a value. A real stack would usually checksize()first or return an optional. - Using the front as the top.
removeFirst()would return the oldest value, which makes a queue, not a stack. The driver's output would then read 10, 20, 30 instead of 30, 20, 10. - Changing the size in
peek. IfpeekusedremoveLast(), the driver's secondSize: 3would be wrong, and later pops would return the wrong values. - Forgetting the underscore in
push. Without it, callers must writepush(value: 10), and the driver'spush(10)does not compile. - Reusing after empty. There is no state to reset when the stack empties. The array is just empty, and the next
appendworks as usual.
Testing
Two more checks with the same class:
let other = MyStack()
other.push(1)
other.push(2)
print(other.peek(), other.peek(), other.size())
2 2 2
After pop() removes the 2, a peek() gives 1 and size() gives 1. A freshly created stack has size() 0 before any push.
