TIP102 Unit 7 Session 1 Standard (Click for link to problem statements)
A wizard is deciphering an ancient scroll and needs to reverse the letters in a word to reveal a hidden message. Write a recursive function to reverse the letters in a given scroll
and return the reversed scroll
. Assume scroll
only contains alphabetic characters.
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
HAPPY CASE
Input: "cigam"
Output: "magic"
Explanation: The string "cigam" reversed is "magic".
Input: "lleps"
Output: "spell"
Explanation: The string "lleps" reversed is "spell".
EDGE CASE
Input: "
Output: "
Explanation: An empty string should return an empty string.
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Reversing a String, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea:
Recursive Approach:
1) Base case: If the string `scroll` is empty, return the empty string.
2) Recursive case:
a) Call the function recursively on the substring `scroll[1:]`.
b) Append the first character `scroll[0]` to the result of the recursive call.
c) Return the reversed string.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def reverse_scroll(scroll):
if len(scroll) == 0:
return scroll
return reverse_scroll(scroll[1:]) + scroll[0]
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
reverse_scroll
function with the input "cigam"
. The function should return "magic"
after recursively reversing each letter."
. The function should return "
, correctly handling the base case.Evaluate the performance of your algorithm and state any strong/weak or future potential work.
O(N)
where N
is the length of the string. The function processes each character exactly once.O(N)
due to the recursion stack. The depth of recursion is proportional to the length of the string.