Given a non-negative integer n and a string name, print the given string exactly n times using recursion.
Standard loops such as for and while must not be used.
Example 1
Input: n = 3, name = "Code"
Output: Code Code Code
Explanation: The function executes three separate times. During each execution, it outputs the given string exactly once, resulting in three consecutive prints.
Example 2
Input: n = 1, name = "Hello"
Output: Hello
Explanation: Because the target count is exactly 1, the string is printed once before the recursive sequence immediately terminates.
Approach
A loop repeats the same task until a condition is met. Recursion can create the same repetition by letting the function call itself with a smaller value.
Here, every call prints the given name once. After printing, the function calls itself with n - 1, meaning one fewer print remains. Once n reaches 0, the required number of prints has been completed, so the recursion stops.
Algorithm
Define a recursive function that receives
nandname. The value ofnrepresents how many times the name is still left to be printed.When
n <= 0, return from the function because no more prints are required. This condition also prevents further calls for a negative value ofn.Print
nameonce for the current recursive call.Call the function again with
n - 1and the samename. Reducingnafter every call brings the recursion closer to the base case.
Dry Run
Print Name N Times Dry Run .png
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: void printName(int n, const string& name) { // Base case: no more prints are left. if (n <= 0) { return; } cout << name << '\n'; // One print is complete, so continue with n - 1. printName(n - 1, name); }};int main() { int n = 3; string name = "Striver"; Solution solution; solution.printName(n, name); return 0;}Complexity Analysis
Time Complexity: O(N), because the function prints the name once for each value from N down to 1.
Space Complexity: O(N), because each recursive call occupies one call-stack frame until the base case is reached.
Interview follow-up Questions
Once n reaches 0, the name has already been printed the required number of times. Using n <= 0 also stops the function safely when a negative value is passed.
Be the first to add a comment.