Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Scala Practice Problems with Solutions

Twelve Scala 3 practice problems with hints and solutions: case classes, pattern matching, Option and Either, folds, tail recursion, lazy lists, futures and type classes.

Reading code teaches you to recognize Scala; writing it teaches you to think in Scala. This lesson collects twelve exercises that practice the ideas from the earlier chapters. Try each problem on paper or in a Scala CLI file before reading the solution, and try to produce the most direct, immutable version you can.

The Scala solutions are read-only here because the site has no Scala compiler. Two runnable Kotlin and Java programs (not Scala) at the end check the algorithms behind several problems, so you can compare outputs. Output comments in the Scala code show the expected result.

How to practice

Read the task Write the signature first.
Think in data Which type models the problem?
Solve it Prefer val, match and map over loops.
Compare Read the solution and refine yours.
1 / 2

Problem 1: A bank account (case classes and Either)

Model an Account with an owner and a balance in cents. Write deposit and withdraw that never mutate: they return a new account or an error message. A withdrawal that would make the balance negative must fail.

Solution

SCALA
case class Account(owner: String, balance: Long):

  def deposit(amount: Long): Either[String, Account] =
    if amount <= 0 then Left("deposit must be positive")
    else Right(copy(balance = balance + amount))

  def withdraw(amount: Long): Either[String, Account] =
    if amount <= 0 then Left("withdrawal must be positive")
    else if amount > balance then Left(s"insufficient funds: balance is $balance")
    else Right(copy(balance = balance - amount))

val result =
  for
    a1 <- Account("Ann", 1000).deposit(500)
    a2 <- a1.withdraw(300)
  yield a2

println(result)   // Right(Account(Ann,1200))

The chain uses copy (Case Classes) and a for-comprehension over Either (For-Comprehensions).

Problem 2: The last element (pattern matching on lists)

Write last[A](xs: List[A]): Option[A] using recursion and pattern matching, without .last or indexing.

Solution

SCALA
@scala.annotation.tailrec
def last[A](xs: List[A]): Option[A] = xs match
  case Nil => None
  case x :: Nil => Some(x)
  case _ :: tail => last(tail)

println(last(List(1, 2, 3)))   // Some(3)
println(last(List.empty[Int])) // None

Problem 3: Shape perimeter (ADTs)

Define a closed family Circle(radius), Rectangle(width, height) and Triangle(a, b, c) and a function perimeter over it. What happens when you add Square(side) later?

Solution

SCALA
enum Shape:
  case Circle(radius: Double)
  case Rectangle(width: Double, height: Double)
  case Triangle(a: Double, b: Double, c: Double)

import Shape.*

def perimeter(s: Shape): Double = s match
  case Circle(r) => 2 * math.Pi * r
  case Rectangle(w, h) => 2 * (w + h)
  case Triangle(a, b, c) => a + b + c

println(perimeter(Rectangle(3, 4)))   // 14.0

After you add case Square(side: Double) to the enum, the compiler warns that perimeter is not exhaustive. That warning is the benefit of a sealed hierarchy (Enums and Sealed ADTs).

Problem 4: FizzBuzz with a tuple match

Print the numbers 1 to 15, replacing multiples of 3 with Fizz, multiples of 5 with Buzz and multiples of both with FizzBuzz, with no if.

Solution

SCALA
def fizzBuzz(n: Int): String = (n % 3, n % 5) match
  case (0, 0) => "FizzBuzz"
  case (0, _) => "Fizz"
  case (_, 0) => "Buzz"
  case _ => n.toString

println((1 to 15).map(fizzBuzz).mkString(", "))
// 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz

Matching on a tuple of the two remainders makes the four cases obvious.

Problem 5: Compose a pipeline (higher-order functions)

Write pipeline[A](fs: List[A => A]): A => A that returns one function applying every function in order. An empty list gives the identity function.

Solution

SCALA
def pipeline[A](fs: List[A => A]): A => A =
  fs.foldLeft(identity[A])(_ andThen _)

val clean = pipeline[String](List(_.trim, _.toLowerCase, _.replace(' ', '-')))
println(clean("  Hello Big World "))   // hello-big-world

The fold starts with identity and appends each function with andThen (Higher-Order Functions).

Problem 6: Run-length encoding (folds)

Encode a string as a list of (Char, Int) pairs where consecutive equal characters are merged: "aaabccdd" becomes List(('a',3), ('b',1), ('c',2), ('d',2)).

Solution

SCALA
def runLength(s: String): List[(Char, Int)] =
  s.foldRight(List.empty[(Char, Int)]) {
    case (c, (d, n) :: rest) if c == d => (d, n + 1) :: rest
    case (c, acc) => (c, 1) :: acc
  }

println(runLength("aaabccdd"))   // List((a,3), (b,1), (c,2), (d,2))

Folding from the right means each character can look at the group already built to its right. A second solution: s.toList.groupBy loses order, so it is not suitable.

Problem 7: Balanced parentheses (tail recursion)

Check whether a string has balanced (), [] and {}. Use a stack, but keep it immutable.

Solution

SCALA
import scala.annotation.tailrec

def balanced(s: String): Boolean =
  val pairs = Map(')' -> '(', ']' -> '[', '}' -> '{')

  @tailrec
  def loop(chars: List[Char], stack: List[Char]): Boolean = chars match
    case Nil => stack.isEmpty
    case c :: rest if "([{".contains(c) => loop(rest, c :: stack)
    case c :: rest if pairs.contains(c) =>
      stack match
        case top :: below if top == pairs(c) => loop(rest, below)
        case _ => false
    case _ :: rest => loop(rest, stack)

  loop(s.toList, Nil)

println(balanced("{[()]}"))   // true
println(balanced("([)]"))     // false
println(balanced("(("))       // false

A List used as a stack gives cheap push (::) and pop (pattern match on the head).

Bonus problem: An Option chain (flatMap)

Given def parse(s: String): Option[Int] and def half(n: Int): Option[Int] (only even numbers have a half), compute the half of the parsed number, or None.

Solution

SCALA
def parse(s: String): Option[Int] = s.toIntOption
def half(n: Int): Option[Int] = if n % 2 == 0 then Some(n / 2) else None

def parseHalf(s: String): Option[Int] =
  for
    n <- parse(s)
    h <- half(n)
  yield h

println(parseHalf("10"))   // Some(5)
println(parseHalf("7"))    // None
println(parseHalf("x"))    // None

Problem 8: Lazy Fibonacci

Define the infinite sequence of Fibonacci numbers lazily and print the first ten.

Solution

SCALA
lazy val fibs: LazyList[BigInt] =
  BigInt(0) #:: BigInt(1) #:: fibs.zip(fibs.tail).map((a, b) => a + b)

println(fibs.take(10).toList)   // List(0, 1, 1, 2, 3, 5, 8, 13, 21, 34)
println(fibs(100))              // 354224848179261931

A LazyList computes elements on demand and remembers them. The definition refers to itself: each element is the sum of the two before it.

Problem 9: Group anagrams

Group words that are anagrams of each other: List("listen", "silent", "enlist", "google", "gogole", "cat", "act") gives three groups.

Solution

SCALA
def anagramGroups(words: List[String]): List[List[String]] =
  words.groupBy(_.sorted).values.toList.sortBy(_.head)

println(anagramGroups(List("listen", "silent", "enlist", "google", "gogole", "cat", "act")))
// List(List(cat, act), List(google, gogole), List(listen, silent, enlist))

Words are anagrams exactly when their sorted letters are equal, so the sorted word is the group key. groupBy keeps the original order inside each group.

Problem 10: Parallel sum with Futures

Split a list of 1,000,000 numbers into four chunks, sum each chunk in its own Future, and combine the results.

Solution

SCALA
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.*

val numbers = (1 to 1_000_000).toList
val chunks = numbers.grouped(250_000).toList

val partials: List[Future[Long]] = chunks.map(chunk => Future(chunk.foldLeft(0L)(_ + _)))
val total: Future[Long] = Future.sequence(partials).map(_.sum)

println(Await.result(total, 5.seconds))   // 500000500000

Future.sequence turns a List[Future[Long]] into a Future[List[Long]]. All four futures start when partials is built, so they run in parallel (Futures and Promises). Await is acceptable here because it is at the edge of a main-like script.

Problem 11: A Monoid type class

Define a Monoid[A] with empty and combine, instances for Int (sum) and String (concatenation), and combineAll(items: List[A]) that works for any type that has an instance.

Solution

SCALA
trait Monoid[A]:
  def empty: A
  def combine(x: A, y: A): A

given Monoid[Int] with
  def empty = 0
  def combine(x: Int, y: Int) = x + y

given Monoid[String] with
  def empty = ""
  def combine(x: String, y: String) = x + y

def combineAll[A](items: List[A])(using m: Monoid[A]): A =
  items.foldLeft(m.empty)(m.combine)

println(combineAll(List(1, 2, 3, 4)))        // 10
println(combineAll(List("sc", "a", "la")))   // scala

This is the pattern from Type Classes and Givens. Extend it with given [A: Monoid]: Monoid[Option[A]] and a Monoid[Map[K, V]].

Problem 12: Word-length statistics

Given a sentence, return a Map[Int, List[String]] from word length to the distinct words of that length, sorted alphabetically.

Solution

SCALA
def byLength(sentence: String): Map[Int, List[String]] =
  sentence.toLowerCase.split("\\W+").toList.filter(_.nonEmpty).distinct
    .groupBy(_.length)
    .view.mapValues(_.sorted).toMap

val stats = byLength("The quick brown fox jumps over the lazy dog")
println(stats(3))   // List(dog, fox, the)
println(stats(5))   // List(brown, jumps, quick)

Check the algorithms here

The programs below are not Scala (Kotlin and Java). They run the same algorithms as Problems 4, 6, 7 and 9, so you can compare the outputs shown above.

Kotlin Kotlin: FizzBuzz, run-length encoding, balanced brackets (Kotlin, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Java Java: group anagrams and a lazy Fibonacci stream (Java, not Scala)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Problem 6, why is foldRight convenient for run-length encoding?

    Building from the right lets a character check the head of the accumulated list and extend it, producing the groups in original order.
  2. 2. What does LazyList give you in the Fibonacci example?

    A LazyList evaluates its tail only when needed and caches results.
  3. 3. Why does Problem 10 create all four futures before waiting?

    Creating the futures starts the work immediately on the thread pool, so combining them afterwards waits for parallel results.
  4. 4. What is the best way to approach a practice problem?

    Struggling with the problem first makes the solution stick. Then compare and refine.

Summary

  • The problems practice case classes and Either, list recursion, ADTs, tuple matches, folds, Option chains, lazy lists, futures and type classes.
  • Prefer immutable data, small pure functions and pattern matching; use @tailrec where a loop would be needed.
  • After each solution, ask what the compiler checks for you, then try an extension.
  • Keep going: rebuild the projects with new features, solve problems from coding platforms in Scala, and read open-source Scala code.

Next: Back to the Scala track