Print 1 to N and N to 1 With a Single Recursive Function

Implement oneToNThenBackToOne

Given a positive integer n, 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.

Example 1:

Input: n = 4

Output: [1,2,3,4,4,3,2,1]

Example 2:

Input: n = 6

Output: [1,2,3,4,5,6,6,5,4,3,2,1]

Example 3:

Input: n = 2

Output: [1,2,2,1]

+ 2 hidden test cases run on Submit.

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

n =

4