#3456
Find Special Substring of Length K
EasyStringSliding WindowTwo Pointers
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)
Use a sliding window approach to efficiently check for valid substrings without redundant checks.
⚙️
Algorithm
3 steps- 1Step 1: Traverse the string while counting consecutive characters.
- 2Step 2: When a sequence of k identical characters is found, check the characters before and after.
- 3Step 3: Return true if conditions are met, otherwise continue.
solution.py12 lines
1def has_special_substring(s, k):
2 n = len(s)
3 count = 1
4 for i in range(1, n):
5 if s[i] == s[i - 1]:
6 count += 1
7 else:
8 count = 1
9 if count == k:
10 if (i == k - 1 or s[i - k] != s[i]) and (i + 1 == n or s[i + 1] != s[i]):
11 return True
12 return Falseℹ
Complexity note: The complexity is O(n) as we traverse the string only once, maintaining a count of consecutive characters.
- 1Look for consecutive characters efficiently.
- 2Check boundaries to ensure distinct characters.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.