Find Special Substring of Length K - Problem

You're given a string s and an integer k. Your task is to find a special substring of exactly length k that meets these requirements:

  1. The substring contains only one distinct character (like "aaa" or "bbb")
  2. If there's a character immediately before the substring, it must be different from the substring's character
  3. If there's a character immediately after the substring, it must be different from the substring's character

Goal: Return true if such a special substring exists, otherwise return false.

Example: In string "abaaacb" with k=3, the substring "aaa" at positions 2-4 is special because it's surrounded by different characters ('b' and 'c').

Input & Output

example_1.py โ€” Basic Special Substring
$ Input: s = "abaaacb", k = 3
โ€บ Output: true
๐Ÿ’ก Note: The substring "aaa" at positions 2-4 consists of identical characters and is surrounded by different characters ('b' before and 'c' after).
example_2.py โ€” No Valid Special Substring
$ Input: s = "abcdef", k = 2
โ€บ Output: false
๐Ÿ’ก Note: No substring of length 2 consists of identical characters, so no special substring exists.
example_3.py โ€” Edge Case at String End
$ Input: s = "abcc", k = 2
โ€บ Output: true
๐Ÿ’ก Note: The substring "cc" at the end consists of identical characters and is preceded by a different character 'b'.

Constraints

  • 1 โ‰ค s.length โ‰ค 104
  • 1 โ‰ค k โ‰ค s.length
  • s consists of lowercase English letters only
  • k cannot exceed the length of the string

Visualization

Tap to expand
abaaacbSpecial Substring!k=3 identical tiles, different boundariesโœ… Found: "aaa" with k=3โ€ข Uniform: All 'a' charactersโ€ข Before: 'b' โ‰  'a'โ€ข After: 'c' โ‰  'a'
Understanding the Visualization
1
Scan the sequence
Move through each tile, tracking consecutive identical colors
2
Detect uniform blocks
When we find k or more consecutive identical tiles, check boundaries
3
Validate boundaries
Ensure the block is surrounded by different colored tiles
4
Return result
True if we find any valid special block, false otherwise
Key Takeaway
๐ŸŽฏ Key Insight: We can solve this efficiently by tracking consecutive character runs and checking boundary conditions only when we find a potential match, achieving O(n) time complexity.
Asked in
Google 28 Amazon 22 Meta 18 Microsoft 15
24.7K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen