LC 3456: Posting cuz it's super intuitive.

February 16, 2025

Find the problem description here. If you would like to read the solution in leetcode platform, find it here.


Intuition

If you think about it, it is just calculating the frequency of same consecutive characters. The frequency is all '1' if no characters are same consecutively.

Example:
index: 01234567
string: baaabaaa
k = 3
freq = 1

we start from index 1,
freq resets to 1 when i = 1 as a != b.

before resetting, check if freq == k
freq = 2 when i = 2 as a == a.
freq = 3 when i = 3 as a == a.
freq resets to 1 when i = 4 as b != a.
before resetting, check if freq == k, it is. so, return true.

done! no isolation checks or anything.


Approach

  • Start with the current count '1', as a single character's frequency is '1'.
  • If the next characters is same as before, increment the count.
  • If it is not equal, simple, check whether the frequency is 'k', if it is.. then you found your special string. Yes, this works.
  • If it is not 'k', then reset the current count to '1' again.

Complexity

  • Time complexity: O(n)O(n)

  • Space complexity: O(1)O(1)


Code

class Solution {
public:
    bool hasSpecialSubstring(string s, int k) {
        int n = s.size();
        int currCount = 1;
        for (int i = 1; i < n; ++i) {
            // calculating the frequency of consecutive characters
            if (s[i] == s[i - 1])   currCount++;
            else {
                // if they reached k then, special
                if (currCount == k) return true;
                // reset
                currCount = 1;
            }
        }
        // checking any trailing consecutive characters
        if (currCount == k) return true;

        return false;
    }
};

good luck!