Start learning free

LESSON 66 OF 70 · PROJECTS: OBJECT-ORIENTED

Stack Impl in Scala: Build a MyStack Class with ArrayBuffer

Practice Read the full explanation

A stack is a pile where you only touch the top: the last value you put in is the first one you take out (LIFO, last in, first out), like a pile of plates. Build a class MyStack that stores whole numbers in a private val data = scala.collection.mutable.ArrayBuffer[Int]() and offers four operations.

The methods:

  • def push(value: Int): Unit
  • def pop(): Int
  • def peek(): Int
  • def size(): Int

Rules:

  • push puts the value on top of the stack. It returns nothing.
  • pop removes the top value (the one pushed last) and returns it.
  • peek returns the top value but leaves it on the stack, so the size does not change.
  • size returns how many values are on the stack. A new stack has size 0, and after popping everything the size is 0 again.
  • The stack keeps working after it becomes empty: you can push again.
  • Calling pop or peek on an empty stack is not part of this exercise and the tests never do it. (In Scala, reading an empty buffer throws an IndexOutOfBoundsException.)

You start with: The starter already contains the code that uses your stack (below).

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())

Expected output:

Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1

Reading the output: after pushing 10, 20 and 30 the top is 30 and the size 3. Popping gives 30, leaving size 2. Two more pops give 20 and then 10 (last in, first out), the stack is empty (size 0), and after pushing 7 the top is 7 and the size 1.


The top of the stack is the end of the list: adding and removing at the end is fast, and the last value pushed is always the last element.

ArrayBuffer has += to add, data(i) to read and remove(index); the last index is data.size - 1. Save the last value in a variable before remove, then return it.

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
    }
}

STEP 1 OF 12
    Ctrl + Enter to check

    SCALA · PROJECTS: OBJECT-ORIENTED

    Stack Impl in Scala, explained

    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): Unit puts a value on top.
    • pop(): Int removes the top value and returns it.
    • peek(): Int returns the top value and leaves it in place.
    • size(): Int returns 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

    1. Declare the class MyStack. The driver's MyStack() builds one stack from it, and each object has its own buffer.
    2. Add private val data = scala.collection.mutable.ArrayBuffer[Int](). A val is 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, and ArrayBuffer lives in the mutable package.
    3. Write the header of push with an Int parameter value and the result type Unit, Scala's "gives back nothing".
    4. Append the value with data += value.
    5. Write the header of pop, which returns an Int. Its body takes three lines.
    6. 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.
    7. Remove the last element with data.remove(data.size - 1). The value is already saved, so nothing is lost.
    8. Return top, the value the caller asked for.
    9. Write peek, again returning an Int.
    10. Return the last element without removing it: the same read as in pop, minus the removal.
    11. Write size with an Int result.
    12. 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 an ArrayBuffer appends in place and works on a val, because it changes the buffer, not the variable. On an immutable Set or Map, += only works on a var, because it builds a new collection and reassigns the variable.
    • remove(index) returns the element it removes. So data.remove(data.size - 1) could be the whole body of pop. 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 pop or peek on an empty stack, the index is -1 and the buffer throws an IndexOutOfBoundsException with the message -1 is out of bounds (min 0, max -1).
    • Method names. Calling s.size() with brackets works because size is declared with an empty parameter list. Inside the class, data.size is 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, not data.size. Reading at data.size throws an exception.
    • Removing before saving. If pop removes the element first, the value is gone and there is nothing left to return. Save it, or use the value that remove returns.
    • A peek that removes. After peek the 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 ArrayBuffer name without the package. Writing ArrayBuffer[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. Then peek() returns 2 and size() returns 2.
    • Push 5, pop() returns 5, size() returns 0. Push 9 and peek() 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 remove returns.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free