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 of Length K INPUT String s = "aabbbcc" a 0 a 1 b 2 b 3 b 4 c 5 c 6 k=3 substring Input Values: s = "aabbbcc" k = 3 Conditions to check: 1. Length exactly k 2. One distinct char 3. Different neighbors 4. Exactly k consecutive ALGORITHM STEPS 1 Iterate through string Scan each character 2 Count consecutive Track same char runs 3 Check run length If count == k, valid! 4 Verify boundaries Neighbors must differ Execution Trace: i=0: a, count=1 i=1: a, count=2 i=2: b, count=1 (reset) i=3: b, count=2 i=4: b, count=3 == k Found! "bbb" at [2-4] s[1]='a' != 'b', s[5]='c' != 'b' FINAL RESULT Special substring found: "bbb" Verification: [OK] Length = 3 (equals k) [OK] Single char: 'b' [OK] Before: 'a' != 'b' [OK] After: 'c' != 'b' [OK] Exactly 3 b's (not more) Output: true Key Insight: Track consecutive character runs with a counter. When count equals k, verify the run ends exactly at that length (next char is different or end of string). This ensures we find substrings of EXACTLY length k, not longer. Time: O(n), Space: O(1) - single pass with constant extra space. TutorialsPoint - Find Special Substring of Length K | Optimal Solution
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