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: last in, first out, like a pile of plates. You build a class MyStack that stores whole numbers in a private ArrayBuffer[Int] and offers four operations:
push(value: Int): Unitputs a value on top.pop(): Intremoves the top value and returns it.peek(): Intreturns the top value and leaves it in place.size(): Intreturns how many values are stacked.
The driver pushes 10, 20 and 30. The top is then 30 and the size is 3. The driver then pops three times, printing Pop: 30, Pop: 20 and Pop: 10, which leaves an empty stack of size 0. After pushing 7, the top is 7 and the size is 1. The stack keeps working after it has been emptied.
The tests never call pop or peek on an empty stack, so you don't need to handle that case.
Approach: the end of the buffer is the top
An ArrayBuffer is a growable list backed by an array. It is cheap to add to or remove from its end and expensive to do either at the front, because every other element has to shift. So the stack's top should be the end of the buffer: pushing appends, popping removes the last element, and the last value pushed is always the last element.
The class keeps the buffer private. Outside code can only use the four methods, so nobody can reorder the values and break the last-in, first-out rule.
Step by step
- Declare the class
MyStack. The driver'sMyStack()builds one stack from it, and each object has its own buffer. - Add
private val data = scala.collection.mutable.ArrayBuffer[Int](). Avalis enough: the buffer's contents change, but the variable always refers to the same buffer. The full name is needed because Scala's default collections are immutable, andArrayBufferlives in themutablepackage. - Write the header of
pushwith anIntparametervalueand the result typeUnit, Scala's "gives back nothing". - Append the value with
data += value. - Write the header of
pop, which returns anInt. Its body takes three lines. - Save the top first:
val top = data(data.size - 1). Scala reads an element with round brackets, and the last index is one less than the size: with 3 values it is 2. - Remove the last element with
data.remove(data.size - 1). The value is already saved, so nothing is lost. - Return
top, the value the caller asked for. - Write
peek, again returning anInt. - Return the last element without removing it: the same read as in
pop, minus the removal. - Write
sizewith anIntresult. - Return
data.size. There is one buffer element per stacked value, so the buffer's size is the stack's size.
The solution in Scala
class MyStack {
private val data = scala.collection.mutable.ArrayBuffer[Int]()
def push(value: Int): Unit = {
data += value
}
def pop(): Int = {
val top = data(data.size - 1)
data.remove(data.size - 1)
return top
}
def peek(): Int = {
return data(data.size - 1)
}
def size(): Int = {
return data.size
}
}
class Solution {
def mainFunction(): Unit = {
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())
}
}
Scala details
+=on anArrayBufferappends in place and works on aval, because it changes the buffer, not the variable. On an immutableSetorMap,+=only works on avar, because it builds a new collection and reassigns the variable.remove(index)returns the element it removes. Sodata.remove(data.size - 1)could be the whole body ofpop. The reference solution reads the value first and removes it second, which makes each step visible. Both give the same results.- Reading with
data(i). Round brackets are a method call on the buffer, not special syntax like Java's square brackets. - Empty stacks. The lesson's tests avoid them. If you do call
poporpeekon an empty stack, the index is -1 and the buffer throws anIndexOutOfBoundsExceptionwith the message-1 is out of bounds (min 0, max -1). - Method names. Calling
s.size()with brackets works becausesizeis declared with an empty parameter list. Inside the class,data.sizeis the buffer's own method, a different one.
Complexity
Every operation is constant time on average. push appends to the end of the buffer, which is amortised O(1): the occasional resize costs more, but it is rare enough to average out. pop, peek and size each touch only the last element or the buffer's length, so they take O(1). The stack uses O(n) space for n stored values.
Had the top been the front of the buffer, push and pop would shift every element and cost O(n). That is why the end is the top.
Edge cases and common mistakes
- Off-by-one index. The last element is at
data.size - 1, notdata.size. Reading atdata.sizethrows an exception. - Removing before saving. If
popremoves the element first, the value is gone and there is nothing left to return. Save it, or use the value thatremovereturns. - A
peekthat removes. Afterpeekthe size must be unchanged. The driver checks this by printing the size right after. - Pushing after emptying. The stack must work again after becoming empty. With a buffer there is nothing to reset, so this works without extra code.
- Using the default
ArrayBuffername without the package. WritingArrayBuffer[Int]()alone fails to compile unless you import it, because it isn't in scope by default.
Testing
Try these on a fresh stack:
- Push 1, 2, 3, then
pop(): it returns 3. Thenpeek()returns 2 andsize()returns 2. - Push 5,
pop()returns 5,size()returns 0. Push 9 andpeek()returns 9.
Key takeaways
- A stack is last in, first out: all the action is at one end.
- For an
ArrayBuffer, the end is the cheap end, so it is the top. - Read the top value before you remove it, or use the value that
removereturns.
