AlgoInsight

DSA problem

Print 1 to N Using Recursion (No Loops)

EasyRecursionPattern: RecursionbeginnerFree

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

Example 1
Input: N = 5
Output: [1, 2, 3, 4, 5]
Explanation: The recursion descends to n = 0 (base case), then appends 1, 2, 3, 4, 5 while unwinding, producing ascending order.
Example 2
Input: N = 1
Output: [1]
Explanation: A single recursive step past the base case appends 1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

recursion

Browse all DSA problems