#2060
Check if an Original String Exists Given Two Encoded Strings
HardStringDynamic ProgrammingTwo PointersString Parsing
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a two-pointer technique to compare the segments of both encoded strings efficiently. It checks if the segments can match by considering the possible lengths of numeric segments.
⚙️
Algorithm
3 steps- 1Step 1: Parse both strings into segments of letters and numbers.
- 2Step 2: Use two pointers to traverse both segments simultaneously.
- 3Step 3: For each numeric segment, check if it can be matched with the corresponding letter segments by considering all possible splits.
solution.py23 lines
1def canEncode(s1, s2):
2 def parse(s):
3 import re
4 return re.findall(r'\D+|\d+', s)
5 segments1 = parse(s1)
6 segments2 = parse(s2)
7 i, j = 0, 0
8 while i < len(segments1) and j < len(segments2):
9 if segments1[i].isdigit() and segments2[j].isdigit():
10 return False
11 if segments1[i].isdigit():
12 length = int(segments1[i])
13 if length < len(segments2[j]):
14 return False
15 segments2[j] = segments2[j][length:]
16 if not segments2[j]:
17 j += 1
18 else:
19 if segments1[i] != segments2[j]:
20 return False
21 i += 1
22 j += 1
23 return i == len(segments1) and j == len(segments2)ℹ
Complexity note: The optimal solution runs in linear time as it processes each segment only once, making it efficient for large inputs.
- 1Understanding how to parse and interpret segments is crucial for solving this problem.
- 2Numeric segments can represent multiple possible lengths, leading to various interpretations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.