Foundations Recursion basics
37. Print Something N Times with Recursion
Easy
Given a positive integer n, return the whole numbers from 1 to n as a list, in increasing order:
1, 2, 3, …, n
The title says print, but here you return the numbers instead of printing them.
Solve it with recursion: a function that calls itself, with no loop. Recursion is the point of this problem.
Example 1
Input: n = 6
Output:
[1,2,3,4,5,6]Explanation: The list starts at 1 and ends with n itself, 6.
Example 2
Input: n = 1
Output:
[1]Explanation: The smallest input gives a list with just one number.
Example 3
Input: n = 12
Output:
[1,2,3,4,5,6,7,8,9,10,11,12]Check your understanding
Work out the answer for this input before you write any code.
n = 4
Constraints
1 ≤ n ≤ 105
Clarifying questions
What you would ask an interviewer before writing any code.