Reverse User Comments Queue - codepath/compsci_guides GitHub Wiki

TIP102 Unit 3 Session 1 Standard (Click for link to problem statements)

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q: What is the input to the problem?
    • A: The input is a list of strings, where each string represents a comment.
  • Q: What is the expected output?
    • A: The output is a list of strings where the comments are in reverse order compared to the input.
  • Q: What data structure should be used to reverse the comments?
    • A: A stack should be used to reverse the order of the comments.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Utilize a stack to reverse the order of the comments in the queue.

1. Initialize an empty stack to temporarily store the comments.
2. Iterate through each comment in the input list:
   1. Push each comment onto the stack.
3. Initialize an empty list to hold the reversed comments.
4. Pop elements from the stack one by one, appending each to the reversed comments list.
5. Once the stack is empty, return the reversed comments list.

⚠️ Common Mistakes

  • Forgetting to pop all elements from the stack before returning the reversed list.
  • Not handling the input correctly, such as modifying the input list instead of creating a new one.
  • Confusing the order in which comments are pushed onto the stack and then popped off.

I-mplement

def reverse_comments_queue(comments):
  stack = []
  reversed_comments = []

  for comment in comments:
    stack.append(comment)

  while stack:
    reversed_comments.append(stack.pop())

  return reversed_comments