oneby7

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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.