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 why it is called LIFO: last in, first out. Think of a pile of plates: you add to the top and you take from the top.
The lesson asks for a class MyStack that stores whole numbers in a private mutableListOf<Int>() 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 and leaves it on the stack;size(): Intsays how many values are on the stack.
The driver pushes 10, 20 and 30, so the top is 30 and the size is 3. It pops 30, leaving size 2, then pops 20 and 10. The stack is empty with size 0. Pushing 7 afterwards works as normal, so the top is 7 and the size is 1. The output:
Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1
Approach
A list already keeps values in order, so a stack only has to decide which end is the top. Use the end of the list. Adding at the end and removing from the end are the cheap operations on a MutableList, and the last value pushed is always the last element. The top of the stack is therefore data[data.size - 1].
Putting the top at the front of the list would also work, but every push and pop would have to shift all the other elements. The end of the list avoids that.
The list is private. Outside code can only use push, pop, peek and size, so it cannot reach into the middle of the pile. That restriction is what makes it a stack and not just a list.
Step by step
- Declare the class
MyStack. The driver'sMyStack()builds one object from it, and each object has its own list. - Add the storage:
private val data = mutableListOf<Int>(). It is avalbecause the list's contents change but the variable never has to point to a different list. - Write
push. It takes anIntnamedvalue. A Kotlin function that returns nothing needs no return type. - Add to the end with
data.add(value). - Write
pop, which returns anInt. It must do two things: give back the top value and take it off the stack. - Save the top first in a
val top, read from the last index, which is one less than the size. With three values the last index is 2. - Remove it with
data.removeAtat that same index. The value is already saved, so nothing is lost. - Return
top. - Write
peek, which returns anInt. - Return the last item without removing it. It is the same read as in
pop, minus the removal. - Write
size, which returns anInt. - Return
data.size. One list item is one stack value.
The solution in Kotlin
class MyStack {
private val data = mutableListOf<Int>()
fun push(value: Int) {
data.add(value)
}
fun pop(): Int {
val top = data[data.size - 1]
data.removeAt(data.size - 1)
return top
}
fun peek(): Int {
return data[data.size - 1]
}
fun size(): Int {
return data.size
}
}
class Solution {
fun mainFunction() {
val s = MyStack()
s.push(10)
s.push(20)
s.push(30)
println("Top: " + s.peek())
println("Size: " + s.size())
println("Pop: " + s.pop())
println("Size: " + s.size())
println("Pop: " + s.pop())
println("Pop: " + s.pop())
println("Empty size: " + s.size())
s.push(7)
println("Top: " + s.peek())
println("Size: " + s.size())
}
}
Kotlin details
mutableListOf<Int>()creates an empty list that can grow and shrink. A plainlistOfwould give a read-only list with noaddorremoveAt. The type argument<Int>is needed because there are no elements to infer it from.data[i]is Kotlin's indexing syntax forget(i).- Two
vals doing different jobs.private val datanever gets reassigned, whileval topholds one saved value for the length of the call. Neither needsvar. - Integer printing.
"Pop: " + s.pop()joins a string and anInt, and Kotlin converts the number to text for you.
Complexity
Every operation runs in constant time. push appends to the end of the list, which is O(1) on average: occasionally the list has to grow its storage, but that cost is spread over many pushes. pop removes the last element, so no other element moves, which is O(1). peek and size are single reads, also O(1). The stack uses O(n) space for the n values it holds.
Edge cases and common mistakes
- Removing before saving. If
popcallsremoveAtfirst, the value is gone. Read it intotopfirst, then remove, then return. - Off-by-one on the last index. The last index is
data.size - 1, notdata.size. Reading atdata.sizegoes one past the end. - Peek that removes.
peekmust leave the size unchanged. In the driver,peekshows 30 with size 3, and the nextpopstill returns 30. - Reusing an emptied stack. After popping everything, the size is 0 and a new
pushworks. With 7 pushed, the top is 7 and the size 1. - Popping an empty stack. The lesson's tests never do this. With this solution,
poporpeekon an empty stack throws anIndexOutOfBoundsExceptionwith the messageIndex -1 out of bounds for length 0, because the indexdata.size - 1is -1.
Testing
Push 1, 2 and 3, then pop until size() reaches 0. The values come out as [3, 2, 1], the reverse of the order they went in. That reversal is the quickest way to see that the stack is last in, first out.
