#844
Backspace String Compare
EasyTwo PointersStringStackSimulationTwo PointersStackString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses two pointers to traverse both strings from the end to the beginning, handling backspaces directly without needing to build new strings. This approach is efficient and avoids unnecessary space usage.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two pointers at the end of both strings.
- 2Step 2: Traverse both strings backwards, skipping characters that are backspaced based on the '#' count.
- 3Step 3: Compare the characters at both pointers when they are not skipped. If they differ, return false. If both pointers reach the start of the strings simultaneously, return true.
solution.py23 lines
1def backspaceCompare(s: str, t: str) -> bool:
2 def next_valid_index(string, index):
3 skip = 0
4 while index >= 0:
5 if string[index] == '#':
6 skip += 1
7 elif skip > 0:
8 skip -= 1
9 else:
10 break
11 index -= 1
12 return index
13 i, j = len(s) - 1, len(t) - 1
14 while i >= 0 or j >= 0:
15 i = next_valid_index(s, i)
16 j = next_valid_index(t, j)
17 if i >= 0 and j >= 0 and s[i] != t[j]:
18 return False
19 if (i >= 0) != (j >= 0):
20 return False
21 i -= 1
22 j -= 1
23 return Trueℹ
Complexity note: This complexity is linear because we traverse each string once, and we do not use any extra space that grows with input size.
- 1Understanding how to handle backspaces is crucial.
- 2Simulating the typing process can help visualize the problem.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.