Find Special Substring of Length K - Problem

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.

Input & Output

Example 1 — Valid Substring
$ Input: s = "aabbbcc", k = 3
Output: true
💡 Note: Substring "bbb" at position 2-4 has length 3, all same character 'b', with different characters before (s[1]='a') and after (s[5]='c').
Example 2 — No Valid Substring
$ Input: s = "aaabbbccc", k = 4
Output: false
💡 Note: No substring of length 4 with identical characters exists. Longest runs are of length 3.
Example 3 — Boundary Violation
$ Input: s = "aaaaa", k = 3
Output: false
💡 Note: While "aaa" exists, any 3-character substring would have matching characters before or after, violating boundary conditions.

Constraints

  • 1 ≤ s.length ≤ 1000
  • 1 ≤ k ≤ s.length
  • s consists of lowercase English letters only

Visualization

Tap to expand
Find Special Substring: s="aabbbcc", k=3Goal: Find substring of length k with identical characters, isolated from same charactersaabbbccValid substring "bbb"Length = 3 ✓All same character ✓Before: 'a' ≠ 'b' ✓, After: 'c' ≠ 'b' ✓Result: true
Understanding the Visualization
1
Input
String s and target length k
2
Process
Find consecutive identical characters ≥ k length
3
Output
Return true if valid isolated substring exists
Key Takeaway
🎯 Key Insight: Track runs of consecutive identical characters and validate boundary isolation conditions
Asked in
Google 25 Amazon 20 Microsoft 15
12.5K Views
Medium Frequency
~15 min Avg. Time
428 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