Problem Description
Given a string s and an integer k, determine if there exists a substring of length exactly k which consists of only one distinct character, and if present, its immediate neighbors (if any) are different from this character.
Key Insights
- The substring must have k identical characters.
- The character immediately before the substring (if it exists) must differ from the substring’s character.
- The character immediately after the substring (if it exists) must also differ.
- Because the string length is at most 100, a simple linear scan checking every possible substring of length k is efficient.
Space and Time Complexity
Time Complexity: O(n * k), where n is the length of the string (acceptable given n ≤ 100). Space Complexity: O(1), constant extra space is used.
Solution
We iterate over all possible starting indices i such that the substring s[i...i+k-1] is a candidate. For each candidate:
- Check if all characters in s[i...i+k-1] are the same.
- Verify that if i > 0, then s[i-1] is not the same as s[i].
- Verify that if i+k < n, then s[i+k] is not the same as s[i]. If a candidate meets all conditions, return true. If no candidate meets the conditions after scanning the string, return false. This approach uses a simple loop with character comparisons to achieve the result.