Skip to main content
Back to problems
#3456
Easy Algorithms

Find special substring of length k

String
35.1% acceptance
Feb 25, 2026
63
10
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.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn has_special_substring(s: String, k: i32) -> bool {
    let k = k as usize;
    let b = s.as_bytes();
    let n = b.len();
    let mut i = 0;
    while i < n {
      let c = b[i]; let mut j = i;
      while j < n && b[j] == c { j += 1; }
      let run = j - i;
      if run == k { return true; }
      i = j;
    }
    false
  }
}