Recursion Template: Pattern, Code & Cheat Sheet
The Recursion pattern is one of the most frequently tested coding interview patterns. Break problems into smaller identical subproblems. This template gives you a reusable code skeleton, pseudocode, and implementation in multiple languages so you can solve 15+ problems using this single mental model.
Difficulty: Medium | Time Complexity: Varies | Space Complexity: O(recursion depth)
When to Use This Template
Use the Recursion template when you see these signals in a problem:
Prerequisites: Function calls, Stack concept
Problem count on W Code: 15 problems across Easy, Medium, and Hard difficulty levels.
If the problem does not match these signals, consider alternative patterns.
Pseudocode Template
function solve(input):
// Base case
if isBaseCase(input):
return base_result
// Recursive case
smallerResult = solve(smaller_input)
return combine(smallerResult, current)Python Implementation
pythondef solve(input_data): """Recursion solution template.""" result = [] # Implement recursion logic here for item in input_data: # Process each item result.append(item) return result
Java Implementation
javapublic Object solve(Object[] input) { // Recursion template // Implement core logic here return null; }
C++ Implementation
cppauto solve(vector<int>& input) { // Recursion template // Implement core logic return result; }
Variations & Adaptations
The Recursion pattern has several variations you should master:
Variation 1: Linear Recursion
This variation is useful when the problem specifically requires linear recursion. Adapt the main template by modifying the core loop/recursion logic accordingly.
Variation 2: Binary Recursion (Trees)
This variation is useful when the problem specifically requires binary recursion (trees). Adapt the main template by modifying the core loop/recursion logic accordingly.
Variation 3: Divide and Conquer
This variation is useful when the problem specifically requires divide and conquer. Adapt the main template by modifying the core loop/recursion logic accordingly.
Variation 4: Tail Recursion
This variation is useful when the problem specifically requires tail recursion. Adapt the main template by modifying the core loop/recursion logic accordingly.
Common Mistakes & Edge Cases
When implementing Recursion, watch out for:
Edge cases to always test:
Step-by-Step Problem Solving Guide
Frequently Asked Questions
What problems can I solve with the Recursion template?
What is the time complexity of Recursion?
What should I learn before Recursion?
How do I recognize a Recursion problem in an interview?
Practice 15+ Recursion problems on W Code with instant feedback and AI-powered hints. Start your free practice now!
Start Learning Free