Unit 7 Session 1 (Click for link to problem statements)
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: "hello"
Output: "h*e*l*l*o"
Explanation: Stars are inserted between each character.
EDGE CASE
Input: "h"
Output: "h"
Explanation: No stars are added as there's only one character.
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.
This problem is a string manipulation challenge that can be solved using both recursion and iteration:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Given a recursive implementation, write an iterative implementation, to insert '*' between each character of a given string.
**Recursive Approach: (Provided)**
1) Base Case: If the string length is 1 or less, return the string as is.
2) Recursive Case: Return the first character + '*' + recursive call on the rest of the string.
**Iterative Approach:**
1) If the string length is 1 or less, return the string as is.
2) Initialize an empty result string and add the first character.
3) Iterate over the string from the second character to the end:
- Append '*' followed by the current character to the result string.
4) Return the result string.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
# Recursive approach (Provided)
def insert_stars_recursive(s):
if len(s) <= 1:
return s
else:
return s[0] + '*' + insert_stars_recursive(s[1:])
# Iterative approach
def insert_stars_iterative(s):
if len(s) <= 1:
return s
result = s[0]
for char in s[1:]:
result += '*' + char
return result
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
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, as each character is processed once.O(n)
for the recursive approach due to the recursion stack and O(n)
for the iterative approach due to the result string size.