Return the Integers 1 to N Using Recursion Without Loops

Quick Overview

Write a recursive function that returns the integers from 1 to n in ascending order without using any for or while loop. It tests choosing a base case, building a list across recursive calls, and handling Python's recursion depth limit.

Return the Integers 1 to N Using Recursion Without Loops

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: easy

Interview Round: Other

Given a positive integer `n`, write a recursive function that returns all integers from 1 to `n` (inclusive) in ascending order. The function must not use any looping constructs such as `for`, `while`, or `do-while`. Only recursion is allowed to generate the sequence. Return the resulting sequence as a list of integers. ### Function Signature ```python def print_numbers(n: int) -> list[int]: ``` ### Rules - No `for` or `while` loops anywhere in the solution. List comprehensions and generator expressions count as loops. - Recursion must generate the values, so built-ins that produce the sequence for you, such as `list(range(1, n + 1))`, are not allowed. ### Constraints - `1 <= n <= 1000` ### Examples ```text Input: n = 5 Output: [1, 2, 3, 4, 5] ``` The recursion starts at 1, adds one value per call, and stops once the current value passes 5. ```text Input: n = 1 Output: [1] ``` Only the value 1 is produced before the base case stops the recursion.

Overview: Write a recursive function that returns the integers from 1 to n in ascending order without using any for or while loop. It tests choosing a base case, building a list across recursive calls, and handling Python's recursion depth limit.

Nov 24, 2026
easySoftware EngineerOtherCoding & Algorithms
0
0

Given a positive integer n, write a recursive function that returns all integers from 1 to n (inclusive) in ascending order.

The function must not use any looping constructs such as for, while, or do-while. Only recursion is allowed to generate the sequence.

Return the resulting sequence as a list of integers.

Function Signature

def print_numbers(n: int) -> list[int]:

Rules

  • No for or while loops anywhere in the solution. List comprehensions and generator expressions count as loops.
  • Recursion must generate the values, so built-ins that produce the sequence for you, such as list(range(1, n + 1)) , are not allowed.

Constraints

  • 1 <= n <= 1000

Examples

Input: n = 5
Output: [1, 2, 3, 4, 5]

The recursion starts at 1, adds one value per call, and stops once the current value passes 5.

Input: n = 1
Output: [1]

Only the value 1 is produced before the base case stops the recursion.