DSA problem
Print 1 to N Using Recursion (No Loops)
Given an integer N, produce the numbers from 1 to N using recursion only - no loops allowed.
This is the simplest recursion problem and the perfect way to understand how the call stack works. The function calls itself with n - 1 first (going deeper), and only records n after the recursive call returns (on the way back up). Doing the work after the recursive call yields ascending order 1, 2, 3, ..., N; doing it before the call yields descending order N, N-1, ..., 1.
Understanding this distinction - work before recursion vs work after recursion - is fundamental to grasping pre-order vs post-order tree traversals, backtracking, and tail recursion. Here we collect the sequence into a list and return it.
Examples
N = 5[1, 2, 3, 4, 5]N = 1[1]Constraints
- 1 <= N <= 10000
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.