Print 1 to N and N to 1 With a Single Recursive Function
Solve this Problemn, produce the sequence that counts up from 1 to n and then immediately back down from n to 1 — using a single recursive function, with no loops.
The trick is choosing where the "collect the current value" step sits relative to the recursive call. Placing it *before* the recursive call means it executes as the recursion descends — call 1 collects, then calls call 2, which collects, then calls 3, and so on — giving increasing order for free. Placing the exact same statement *again*, this time *after* the recursive call, means it executes as the recursion unwinds — the deepest call finishes and collects first, then the one above it, and so on back up to the top — giving decreasing order. One function, one base case, and the position of two lines relative to a single recursive call produces both directions.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ n ≤ 10 - ◆
No loops are allowed for the intended (recursive) technique — the sequence must be produced by a single recursive function, not two separate ones
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Iterative — Two Separate Loops
OptimalRun one loop from 1 up to n, appending as it goes, then a second loop from n back down to 1, appending again. Straightforward and uses no extra memory beyond the output itself — but it reaches for two independent loops where the classic version of this exercise specifically asks for a single recursive function and no loops at all.
O(n)O(1) extra (beyond the output)1class Solution {
2 public int[] oneToNThenBackToOne(int n) {
3 int[] result = new int[2 * n];
4 int idx = 0;
5 for (int i = 1; i <= n; i++) result[idx++] = i;
6 for (int i = n; i >= 1; i--) result[idx++] = i;
7 return result;
8 }
9}Recursive — Collect Before and After the Call
GoodA single recursive function can produce both directions at once, just by choosing where the "collect" step goes relative to the recursive call. Collecting the current value *before* recursing naturally happens in increasing order, as each call runs before the ones beneath it. Collecting it again *after* the recursive call returns happens in decreasing order, since the deepest call finishes — and does its "after" step — first. One function, one base case, both directions.
O(n)O(n) call-stack space1class Solution {
2 public int[] oneToNThenBackToOne(int n) {
3 List<Integer> result = new ArrayList<>();
4 helper(1, n, result);
5 int[] output = new int[result.size()];
6 for (int i = 0; i < result.size(); i++) output[i] = result.get(i);
7 return output;
8 }
9
10 private void helper(int i, int n, List<Integer> result) {
11 if (i > n) return;
12 result.add(i);
13 helper(i + 1, n, result);
14 result.add(i);
15 }
16}