TIP102 Unit 3 Session 1 Standard (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a queue to reverse the characters of each word while preserving the spaces and word order.
1. Initialize an empty deque (double-ended queue) to hold the characters of each word.
2. Initialize an empty list to build the final result.
3. Iterate through each character in the post:
1. If the character is not a space, enqueue it to the deque.
2. If the character is a space, dequeue all characters from the deque (which reverses the word) and append them to the result list. Then append the space to the result list.
4. After the loop, handle any remaining characters in the deque (i.e., the last word).
5. Join all elements in the result list to form the final string and return it.
⚠️ Common Mistakes
from collections import deque
def edit_post(post):
queue = deque()
result = []
for char in post:
if char != ' ':
queue.append(char) # Enqueue character
else:
while queue:
result.append(queue.pop()) # Dequeue to reverse the word
result.append(' ') # Add the space back after the word is reversed
# Handle the last word (if the string doesn't end with a space)
while queue:
result.append(queue.pop())
return ''.join(result)