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?- A. d y False
- B. ad y True
- C. d y True
- 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
- Problem: Normalise a Unix-style absolute path: collapse repeated slashes, drop '.', and let '..' go up one directory (never above root)…
- Problem: Find the minimum number of brackets to insert so that a string of '(' and ')' becomes balanced. python def minadd(s): open = add…
- Problem: Parcels 1..5 are pushed onto a loading stack in that order (pops may happen at any time). Decide whether a given pop order is…
- Problem: People queue at a single counter; person i wants t[i] tickets, buys one per second and, if still needing more, goes to the back…
- Problem: Regroup a linked list so that all nodes at odd positions (1st, 3rd, …) come first, followed by the even positions, keeping…
- Problem: Rotate a linked list to the right by k places (k may exceed the length). python class Node: def init(self, v, nxt=None): self.v…