TIP102 Unit 7 Session 1 Advanced (Click for link to problem statements)
The deli counter is busy, and orders have piled up. To serve the last customer first, you need to reverse the order of the deli orders. Given a string orders
where each individual order is separated by a single space, write a recursive function reverse_orders()
that returns a new string with the orders reversed.
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: "Bagel Sandwich Coffee"
Output: "Coffee Sandwich Bagel"
Explanation: The words "Bagel Sandwich Coffee" are reversed to "Coffee Sandwich Bagel".
EDGE CASE
Input: "
Output: "
Explanation: An empty string returns 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 Words in 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 list `words` is empty, return an empty string.
2) Base case: If the list `words` has only one word, return that word.
3) Recursive case: Call the helper function on the rest of the list `words[1:]` and append the first word at the end.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def reverse_helper(words):
if len(words) == 0: # Base case: no words left to process
return "
if len(words) == 1: # Base case: only one word left
return words[0]
# Recursive case: reverse the rest and append the first word at the end
return reverse_helper(words[1:]) + " " + words[0]
def reverse_orders(orders):
words = orders.split() # Split the sentence into a list of words
return reverse_helper(words) # Call the external helper function with the list of words
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
reverse_orders
function with the input "Bagel Sandwich Coffee"
. The function should return "Coffee Sandwich Bagel"
after reversing the order of words."
. 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 number of words in the string. The function processes each word exactly once.O(N)
due to the recursion stack and the space needed to store the reversed string. The depth of recursion is proportional to the number of words.