DevPrep

All topics › Algorithms & data structures

What is recursion and why is it dangerous?

Middle PRO

The gist

Recursion is a function calling itself, reducing the problem to a smaller one. It needs a base case (stop condition) and a step that moves toward the base. It is natural for trees, graphs, divide and conquer (merge sort, quicksort), and parsing nested structures (JSON, expressions).

func sumTo(_ n: Int) -> Int { n == 0 ? 0 : n + sumTo(n - 1) }
print(sumTo(10_000))   // 50005000

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store