Week 1 · Day 5 of 42

Two Pointer: String Comparison with Backspaces and String Reversal

"Compare strings with backspaces (#) without building them" → process from the end, count backspaces, skip characters accordingly, then compare. "Reverse something in-place" → left pointer at start, right pointer at end, swap and move inward until they meet.

Sign in to tick off tasks and keep your progress on every device

Two Pointers - String Comparison with Backspaces

Tick the box when you have studied this pattern

How to recall this pattern

"Compare strings with backspaces (#) without building them" → process from the end, count backspaces, skip characters accordingly, then compare.
ab#cS₁i ←ad#cS₂j ←Process from right → left, skip chars after #
  • Process strings from the end. When you hit a "#", count backspaces and skip characters.
  • Compare characters only when both pointers are on non-skipped characters.
  • Simulating from the end avoids building the final string, giving O(1) space.
  • Time: O(n + m), Space: O(1).
Python template and worked solutions

Two Pointers - String Reversal

Tick the box when you have studied this pattern

How to recall this pattern

"Reverse something in-place" → left pointer at start, right pointer at end, swap and move inward until they meet.
helloLRswap
  • Place pointers at start and end of the string (or segment). Swap and move inward.
  • For reversing words: reverse the whole string, then reverse each word individually.
  • Works in-place with O(1) extra space on mutable arrays.
  • Time: O(n), Space: O(1) if array is mutable.
Python template and worked solutions

Solve these

Try each one before reading a solution. Name the pattern out loud first.

Extra practice · 2 more problems

See it move

Spotted a mistake on this page?

Wrong formula, broken animation or confusing wording. Tell us and we will fix it.