Find Special Substring of Length K Problem
#3456
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3456.
You are given a string s and an integer k.
Determine if there exists a substring of length exactly k in s that satisfies the following conditions:
- The substring consists of only one distinct character (e.g.,
"aaa"or"bbb"). - If there is a character immediately before the substring, it must be different from the character in the substring.
- If there is a character immediately after the substring, it must also be different from the character in the substring.
Return true if such a substring exists. Otherwise, return false.
Example 1:
Input: s = "aaabaaa", k = 3
Output: true
Explanation:
The substring s[4..6] == "aaa" satisfies the conditions.
- It has a length of 3.
- All characters are the same.
- The character before "aaa" is 'b', which is different from 'a'.
- There is no character after "aaa".
Example 2:
Input: s = "abc", k = 2
Output: false
Explanation:
There is no substring of length 2 that consists of one distinct character and satisfies the conditions.
Constraints:
1 <= k <= s.length <= 100sconsists of lowercase English letters only.
Solution
Approach: Runs of Equal Characters
A special substring consists of one repeated character that cannot be extended by the same character on either side. So it is exactly a maximal run of equal characters of length k.
Scan the string. At position l, move r forward while s[r] == s[l]; the run has length r - l. If that equals k, return true. Otherwise continue from r. If no run has length k, return false.
Complexity: O(n) time and O(1) extra space.
class Solution:
def hasSpecialSubstring(self, s: str, k: int) -> bool:
l, n = 0, len(s)
while l < n:
r = l
while r < n and s[r] == s[l]:
r += 1
if r - l == k:
return True
l = r
return False