#3330
Find the Original Typed String I
EasyStringTwo PointersSliding WindowHash Map
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 leverages a single pass through the string to count the number of possible original strings. By tracking groups of consecutive characters, we can efficiently determine how many variations can be formed.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a counter to 1 for the original string.
- 2Step 2: Traverse the string while counting consecutive characters.
- 3Step 3: For each group of consecutive characters, if the count is more than 1, increment the counter.
- 4Step 4: Return the counter as the total number of possible original strings.
solution.py12 lines
1def count_possible_originals(word):
2 count = 1
3 n = len(word)
4 i = 0
5 while i < n:
6 j = i
7 while j < n and word[j] == word[i]:
8 j += 1
9 if j - i > 1:
10 count += 1
11 i = j
12 return countℹ
Complexity note: The complexity is O(n) because we only traverse the string once, counting groups of consecutive characters without any nested iterations.
- 1Identifying groups of consecutive characters is crucial for determining possible original strings.
- 2Each group of consecutive characters can contribute to the count of possible original strings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.