Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: In a text editor '#' means backspace (on an empty buffer it does nothing). Compute the final text with a stack.

Problem: In a text editor '#' means backspace (on an empty buffer it does nothing). Compute the final text with a stack.
def typed(s):
    st = []
    for c in s:
        if c == "#":
            if st: st.pop()
        else:
            st.append(c)
    return "".join(st)
print(typed("ab#c##d"), typed("x##yz#"), typed("ab#c##d") == typed("d"))
What is printed?
  1. A. d y False
  2. B. ad y True
  3. C. d y True
  4. D. d yz False

Correct answer: C. d y True

"ab#c##d": a → ab → a → ac → a → (empty) → d. "x##yz#": x → (empty) → the second # is ignored on an empty buffer → y → yz → y. Equal final texts compare True. O(n) with a stack; an O(1)-space version scans both strings from the right while counting pending backspaces.

More Coding Interview Problems questions

Exams that ask this topic