Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 17 / Topic 5 of 12

Recursion and backtracking

Recursion is a function calling itself on a smaller version of the same problem, with a base case that stops the chain and a recursive case that shrinks toward it. Backtracking is recursion with a pattern on top: choose one option, explore what follows from it, then un-choose (backtrack) before trying the next option — so every combination gets a fair, isolated try. Think of a courier planning stop orders: try stop A first, work out the rest of the route assuming A went first, then come back and try stop B first instead — nothing from trying A leaks into the attempt that starts with B.

// A genuinely tail-recursive case: the recursive call is the LAST thing that happens,
// and it carries the running total forward instead of waiting on the call below it.
// `tailrec` asks the compiler to rewrite this into a loop; the compiler warns if it can't.
tailrec fun factorial(n: Long, accumulator: Long = 1L): Long =
    if (n <= 1L) accumulator else factorial(n - 1, n * accumulator)

// NOT tail-recursive: the two recursive calls are combined (added) AFTER they return,
// so `tailrec` would not compile here -- this is left as plain recursion on purpose.
fun fibonacciSlow(n: Int): Long =
    if (n <= 1) n.toLong() else fibonacciSlow(n - 1) + fibonacciSlow(n - 2)
$ kotlinc RecursionBacktrackingDemo.kt -include-runtime -d rb.jar
$ java -jar rb.jar
-- factorial: base case + recursive case, written tailrec --
factorial(6) = 720

-- fibonacci: naive recursion vs memoized --
fibonacciSlow(35)      = 9227465  (13 ms, varies)
fibonacciMemoized(35)  = 9227465  (659 microseconds, varies)
same answer: true

-- backtracking: every pickup order for 3 stops --
  [Kothrud, Baner, Aundh]
  [Kothrud, Aundh, Baner]
  [Baner, Kothrud, Aundh]
  [Baner, Aundh, Kothrud]
  [Aundh, Kothrud, Baner]
  [Aundh, Baner, Kothrud]
total orders: 6 (3! = 6)

-- backtracking with pruning: parcel subsets under a 5 kg bag limit --
  [books] = 2 kg
  [laptop] = 3 kg
  [laptop, books] = 5 kg
  [shoes] = 1 kg
  [shoes, books] = 3 kg
  [shoes, laptop] = 4 kg
  [groceries] = 4 kg
  [groceries, shoes] = 5 kg
combinations that fit: 8

fibonacciSlow re-solves the same smaller fibonacci numbers over and over — its recursion tree doubles in size with every step up, which is why fibonacciSlow(35) is measured in milliseconds while the memoized version (section 12's dynamic-programming idea, used here one topic early) is measured in microseconds for the identical answer. factorial, by contrast, genuinely compiles to a loop: tailrec only rewrites a function whose last action is the recursive call itself (nothing left to do with the result afterward), which is why fibonacciSlow — whose last action is an addition of two recursive calls — can never honestly be marked tailrec. Marking it anyway does not fail the build: kotlinc emits "a function is marked as tail-recursive but no tail calls are found" and two more warnings pointing at each call, then quietly compiles it as ordinary, stack-growing recursion — the exact StackOverflowError risk tailrec exists to remove, silently still present. The last example adds pruning: fittingSubsets returns immediately once currentWeight > limitKg, so it never wastes time exploring a branch that can only get heavier.

⚠️ Every recursive function needs a base case that is actually reachable, tailrec or not. A recursive case that never shrinks toward the base case (or a base case with a typo in its condition) is a StackOverflowError waiting to happen — tailrec removes the stack-depth risk for the one shape it applies to, it does not forgive a broken base case.

Full program: examples/recursion-backtracking/RecursionBacktrackingDemo.kt.

Done here? The practice set for Part 17 — including the solutions — is on the part page.

Search the guide