Print N to 1 and 1 to N
State Preservation / Pre vs. Post RecursionSolved Nov 12, 2025
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 110 pointsSolved (Easy) 0/20Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Watch the concept video if the pattern is new to you.
Step 2
Try it on paper
5–10 minutes, no code yet
ProblemProblem statementImplement two recursive functions:ReadHide
Problem Description
Implement two recursive functions:
- Print numbers from
Ndown to 1. - Print numbers from 1 up to
N.
Code it here
Tab / Shift+Tab indent · ⌘/Ctrl+/ comments · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
The difference between the two is where the print statement is placed relative to the recursive call. Printing before the call manages state, printing after the call uses the returning stack.
Approaches
1. Pre vs. Post Recursion (Optimal) - O(N) ⭐
Idea: Both solutions require N recursive calls, making the time O(N). The difference demonstrates how the call stack functions:
- N to 1: The print statement executes before the recursive call.
- 1 to N: The recursive call is made first, building up the stack. The print statement executes after the recursive call returns, unwinding the stack from 1 to N.
Solution code
import sys
def solve_print_n():
try:
N = int(sys.stdin.readline().strip())
except:
return
# Optimized (1 to N): Post-recursion print
def print_1_to_N(n):
if n == 0:
return
print_1_to_N(n - 1)
print(n, end=" ")
# Brute Force (N to 1): Pre-recursion print
def print_N_to_1(n):
if n == 0:
return
print(n, end=" ")
print_N_to_1(n - 1)
print("N to 1 (Brute):", end=" ")
print_N_to_1(N)
print("\n1 to N (Optimal):", end=" ")
print_1_to_N(N)
print()
if __name__ == "__main__":
solve_print_n()Other ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language