Best Problems on Recursion | Recursion in C++
Recursion - I
Print String in Reverse Objective: To print the string in reverse.
Base Case: If the string is empty:
return;
Reverse print the remaining string using recursion, and print then print the current character.
Time Complexity: O(N2) [ IMP]
Space Complexity: O(N2) [ IMP]
Time complexity will be O(N2) because s.substr(i) takes O(N) times and it is called O(N) times.
Space complexity will be O(N2) because s.substr(i) gives a string of O(N) size and it is called O(N) times.
FollowUp: Try to do this in O(N) time and space. Hint: Pass by reference and
indices.
Move all ‘x’ to the end of the string If the string is empty:
return “ “;
If the current character ch is ‘x’, we add the resultant string + ch,
Else we return ch + resultant string
Time Complexity: O(N2) [ IMP]
Space Complexity: O(N2 ) [ IMP]
Time complexity will be O(N2) because s.substr(i) takes O(N) times and it is called O(N) times.
Space complexity will be O(N2) because s.substr(i) gives a string of O(N) size and it is called O(N) times.
FollowUp: Try to do this in O(N) time and space. Hint: Pass by reference and indices.
Remove Duplicates
If the string is empty: //no duplicates return “”;
If the current character ch is ‘x’, we return resultant string + ch,
Else we return ch + resultant string
Time Complexity: O(N2)
Space Complexity: O(N2)
Time complexity will be O(N2) because s.substr(i) takes O(N) times and it is called O(N) times.
Space complexity will be O(N2) because s.substr(i) gives a string of O(N) size and it is called O(N) times.
Replace Pi If the string is empty:
return “”; If s[0] == ‘p’ and s[1] == ‘i’ :
print(“3.14”)
else:
print(s[0])
Time Complexity: O(N2)
Space Complexity: O(N2)
FollowUp: Try to do this in O(N) time and space. Hint: Pass by reference and indices.
Print all the subsequences
Objective: For each character, we have two choices, either we include it or not.
Time Complexity: O(2n )
Space Complexity: O(2n )
Tower of Hanoi
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
Idea: move all the n-1 tiles to helper, and then place the remaining tile to dest and then place those n-1 tiles back from helper to dest.
Time Complexity: O(2n )
Space Complexity: O(1)
Code for follow-ups:
1. Reverse
2. Replace PI
Comments
Post a Comment