Codepath

Post Compare

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: How should the # character be handled?
    • A: The # character represents a backspace, so the previous character (if any) should be removed.
  • Q: What should happen if there are multiple # characters?
    • A: Each # should remove one preceding character. If there is no character to remove, the text remains unchanged.
  • Q: How should the drafts be compared?
    • A: After processing the drafts by applying the backspaces, the resulting strings should be compared to determine if they are equal.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Use a stack to simulate the typing process, accounting for backspaces, and then compare the final processed strings.

1. Define a helper function `build_final_string(draft)` that processes the draft:
   1. Initialize an empty stack.
   2. Iterate through each character in the draft:
      1. If the character is `#`, pop the top character from the stack (if the stack is not empty).
      2. Otherwise, push the character onto the stack.
   3. Return the stack as the final processed string.
2. In the main function `post_compare`, call `build_final_string` on both `draft1` and `draft2`.
3. Compare the resulting processed strings:
   1. If they are equal, return `True`.
   2. Otherwise, return `False`.

⚠️ Common Mistakes

  • Forgetting to handle consecutive # characters properly.
  • Not checking whether the stack is empty before attempting to pop a character.
  • Comparing drafts directly without processing backspaces.

I-mplement

def build_final_string(draft):
    stack = []
    for char in draft:
        if char == '#':
            if stack:
                stack.pop()  # Simulate backspace
        else:
            stack.append(char)  # Add the character to the stack
    return stack

def post_compare(draft1, draft2):
    # Build the final strings after considering backspaces
    final_draft1 = build_final_string(draft1)
    final_draft2 = build_final_string(draft2)
    
    # Compare the resulting stacks
    return final_draft1 == final_draft2
Fork me on GitHub