TIP102 Unit 3 Session 2 Standard (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
clues
where each element is either an integer representing a booth number or the word "back"
indicating that the participant should backtrack to the previous booth."back"
should remove the most recently visited booth, simulating backtracking.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a stack to simulate the navigation process. Each booth number is pushed onto the stack when visited, and if "back"
is encountered, the last visited booth is removed from the stack.
1. Initialize an empty stack to track the sequence of booths visited.
2. Iterate through the list `clues`:
1. If the clue is an integer (booth number), push it onto the stack.
2. If the clue is `"back"`, pop the top element from the stack if it is not empty.
3. After processing all clues, return the stack, which contains the final sequence of booths visited.
⚠️ Common Mistakes
"back"
is encountered."back"
commands correctly, which could result in an incorrect final sequence.def booth_navigation(clues):
stack = []
for clue in clues:
if clue == "back":
if stack:
stack.pop()
else:
stack.append(clue)
return stack
# Example usage
clues = [1, 2, "back", 3, 4]
print(booth_navigation(clues)) # Output: [1, 3, 4]
clues = [5, 3, 2, "back", "back", 7]
print(booth_navigation(clues)) # Output: [5, 7]
clues = [1, "back", 2, "back", "back", 3]
print(booth_navigation(clues)) # Output: [3]