Print Numbers from N to 1

Solve this Problem
Easy5 min
Topics
Companies
Given a non-negative integer n, return the numbers from n down to 1, in decreasing order. The decrementing loopDecrementing LoopWalking an index from n down to 1, appending each value as it goes — the mirror image of counting up. version is the direct analogue of counting up, just running backward. The range-then-reverseRange, Then ReverseGenerating the easy ascending sequence first, then reversing it — rather than hand-writing a descending loop. version builds the sequence everyone's more used to generating (ascending), then flips it — still O(n) overall, just composed from two simpler, well-known operations instead of one custom loop.

Test Case 1:

Input:n = 5
Output:[5, 4, 3, 2, 1]
Explanation:Every integer from 5 down to 1.

Test Case 2:

Input:n = 1
Output:[1]
Explanation:Just the one number.

Test Case 3:

Input:n = 0
Output:[]
Explanation:No numbers to print.

Constraints

  • ◆0 ≤ n ≤ 1000

Try the Dry Run

Approach & Solutions

For Loop — DecrementingGood

Walk i from n down to 1, appending each value as the loop goes — the mirror image of counting up, just decrementing i instead of incrementing it.

TimeO(n)
SpaceO(n) for the output
1class Solution { 2 public int[] printNToOne(int n) { 3 int[] result = new int[n]; 4 for (int i = n; i >= 1; i--) { 5 result[n - i] = i; 6 } 7 return result; 8 } 9}
Built-in Range, Then ReverseOptimal

Generate the ascending range 1 to n (the easy direction for a built-in range tool) and then reverse it, rather than building the descending sequence by hand with a decrementing loop. C still falls back to the explicit loop, since it has no built-in range or reverse.

TimeO(n)
SpaceO(n)
1class Solution { 2 public int[] printNToOne(int n) { 3 int[] result = java.util.stream.IntStream.rangeClosed(1, n).toArray(); 4 for (int i = 0; i < result.length / 2; i++) { 5 int temp = result[i]; 6 result[i] = result[result.length - 1 - i]; 7 result[result.length - 1 - i] = temp; 8 } 9 return result; 10 } 11}

Related Problems