15% off all plans & roadmaps Use code

See plans

Find Longest Special Substring That Occurs Thrice I

Updated

TL;DR: You need the longest run of one repeated letter that appears at least three times in the string. Split the string into runs of equal letters, and the three longest runs per letter decide the answer.

Problem

You are given a string s made of lowercase English letters.

A string is special if it uses only one character. For example, ddd, zz, and f are special, while abc is not.

Return the length of the longest special substring of s that occurs at least three times, or -1 if no special substring occurs at least three times.

A substring is a contiguous, non-empty sequence of characters inside a string.

Example 1

Input: s = "aaaa"
Output: 2
Explanation: The longest special substring that occurs three times is aa. The occurrences start at indexes 0, 1, and 2. No longer special substring occurs three times.

Example 2

Input: s = "abcdef"
Output: -1
Explanation: No special substring occurs at least three times, so the answer is -1.

Example 3

Input: s = "abcaba"
Output: 1
Explanation: The longest special substring that occurs three times is a. It appears at indexes 0, 3, and 5.

Constraints

  • 3 <= s.length <= 50
  • s consists of only lowercase English letters.

Constraints that matter

  • s.length <= 50 keeps an O(n^4) brute force near 6 million basic steps, so it passes here, but it would not scale.
  • Only 26 letters exist, so a fixed table with three slots per letter costs constant space.
  • Every substring that occurs three times lies inside a run of one letter, so the search can ignore mixed substrings.
  • The answer can be -1, so the best value must start at -1 and not at 0.

View on LeetCode

Hints

Hint 1

Start with the rule that makes the problem small.

Hint 2

Try every substring and check two things.

Solution

Intuition

Start with the rule that makes the problem small. A special substring is made of one letter, so it always sits inside a maximal run of that letter. A run of length L holds L copies of length 1, L - 1 copies of length 2, and so on. Counting these copies is the core of the problem.

Picture a drawer for each letter, holding one ribbon per run of that letter. The drawer is the letter's run list, and you keep only its three longest ribbons while discarding the shorter ones.

The pattern here is a variable-size sliding window over identical characters. The window grows while the next letter matches and closes when the letter changes. Each closed window is a maximal run, and you only need to record its length and letter.

The second observation drives the fast method. If a length k occurs at least three times, then the three longest runs of that letter already give three occurrences of k. Any other run of length at least k would add more, but it is never needed to reach three. So each letter only needs its three longest runs.

Watch the pattern animation

Worked example

Input: s = "aabbaabbaabbaa"
Output: 2
Explanation: The string splits into seven runs: aa, bb, aa, bb, aa, bb, aa. Letter a has four runs of length 2, so the substring aa occurs four times. No run is longer than 2, so no substring of length 3 can occur at all. The answer is 2.

Approach 1: Brute force

Try every substring and check two things. Is it special, and how many times does it occur in s? Keep the longest special substring that occurs at least three times. This is the direct reading of the statement, and it needs no insight.

The cost comes from the counting. For every candidate substring you scan every start position and compare characters again. Most of that work repeats across candidates that share a prefix or a letter.

Steps

  1. Set best to -1.
  2. For each start index i and each end index j greater than i, take sub = s[i:j].
  3. If sub contains a different letter, skip it.
  4. Count the start positions p where s matches sub starting at p.
  5. If the count is at least 3 and len(sub) is larger than best, set best = len(sub).
  6. Return best.

Dry run

Take aabbaabbaabbaa. The pair (i=0, j=2) gives aa, which is special. Scanning start positions finds matches at 0, 4, 8, and 12, so the count is 4. Set best = 2.

Next, aab is not special, so it is skipped. Every other special substring has length 1 or 2, and aaa never appears because no run is longer than 2. The final best is 2, which matches the output.

Complexity

TimeO(n^4)
SpaceO(n)

There are about n^2 / 2 pairs (i, j), where n is the length of s. For each pair, the code scans up to n start positions and compares up to n characters at each one, so one pair costs up to O(n^2). Multiplying gives O(n^4) in the worst case, which happens when s is one repeated letter. The space is the one substring held at a time, which is O(n).

PythonTested in our runner

class Solution:
    def maximumLength(self, s: str) -> int:
        n = len(s)
        best = -1
        for i in range(n):
            for j in range(i + 1, n + 1):
                sub = s[i:j]
                # skip substrings that mix letters
                if len(set(sub)) != 1:
                    continue
                occurrences = 0
                for p in range(n - len(sub) + 1):
                    if s[p:p + len(sub)] == sub:
                        occurrences += 1
                if occurrences >= 3:
                    best = max(best, len(sub))
        return best

The Variable Size (Condition-Based) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Variable Size (Condition-Based)

Part of Sliding Window

Approach 2: Run lengths, then top three per letterOptimalVariable Size (Condition-Based)

What's slow: the brute force rescans the whole string for every candidate. It also rebuilds substrings that repeat a single run. Most of those checks answer the same question about a run that was already measured.

The insight that fixes it: a special substring is a window inside one run. Split s into maximal runs once, and record each run's letter and length. Each letter then has a short list of run lengths. The occurrence count for length k is the sum over that letter's runs of max(0, L - k + 1).

The second part of the insight removes the rest of the work. If some run of length at least k exists beyond the top three, then the top three run lengths per letter give the same answer as the full list. Sort each letter's runs, keep three values, and test lengths from the longest downward.

Why it is correct. A run outside the top three can only add occurrences of k if its length is at least k. In that case the top three runs are each at least as long, so they already supply three copies of k. Runs shorter than k contribute nothing, so dropping them never changes the answer.

Steps

  1. Scan s once and split it into maximal runs of equal letters. Store each run length in a list for its letter.
  2. For each letter, sort its list in descending order and keep the first three values. Pad missing values with 0.
  3. Start k at the largest of the three values and move down to 1.
  4. For the current k, add max(0, b - k + 1) over the three kept values b.
  5. If the total is at least 3, record k as the best for this letter and stop checking smaller k.
  6. Return the largest recorded value across all letters, or -1 if none was recorded.

Dry run

StepBlock scanned (start index)Letter a runsLetter b runs
1aa (index 0)[2][]
2bb (index 2)[2][2]
3aa (index 4)[2, 2][2]
4bb (index 6)[2, 2][2, 2]
5aa (index 8)[2, 2, 2][2, 2]
6bb (index 10)[2, 2, 2][2, 2, 2]
7aa (index 12)[2, 2, 2, 2][2, 2, 2]

After the scan, letter a keeps top three [2, 2, 2]. Start at k = 2: the count is 1 + 1 + 1 = 3, so the best for a is 2. Letter b keeps [2, 2, 2] too, and k = 2 again gives 3. The best across letters is 2, which matches the output.

Complexity

TimeO(n log n)
SpaceO(n)

The scan visits each character once, so splitting into runs costs O(n). Sorting the runs of each letter costs O(r log r) per letter, and the run counts add up to at most n, so the sorts cost O(n log n) in total. For each letter the k loop starts at its longest run, which is at most n, and each step does three additions, and the longest runs of distinct letters are disjoint blocks, so these loops add up to O(n).

PythonTested in our runner

class Solution:
    def maximumLength(self, s: str) -> int:
        n = len(s)
        # runs[c] holds the length of every maximal block of letter c
        runs = {}
        i = 0
        while i < n:
            j = i
            while j < n and s[j] == s[i]:
                j += 1
            runs.setdefault(s[i], []).append(j - i)
            i = j
        best = -1
        for lengths in runs.values():
            lengths.sort(reverse=True)
            # only the three longest runs can decide the answer
            top = lengths[:3] + [0] * (3 - len(lengths[:3]))
            # the answer for this letter is the largest k with 3 or more occurrences
            for k in range(top[0], 0, -1):
                count = sum(max(0, b - k + 1) for b in top)
                if count >= 3:
                    best = max(best, k)
                    break
        return best

Common mistakes

  • best = max(best, k) with best starting at 0 instead of -1. A valid answer of 1 is lost when no substring repeats, and the output should be -1.
  • Counting each run as one occurrence of its full length. A run of length L also holds L - k + 1 copies of every length k up to L, so aaaa contributes to aa.
  • Using s[j] == s[j + 1] without the bound j + 1 < n. The last index reads past the end of the string.
  • Keeping only the longest run per letter. Two runs of length 2 give two occurrences of aa, and a third run is needed to reach three, so keep three runs.
  • Testing count >= 3 only for k equal to the longest run. Smaller lengths can reach three occurrences when the longest run is short of three copies, so scan downward until the count holds.

Edge cases

  • abcdef has no repeated letter, so every letter has one run of length 1. The count for k = 1 is 1, so the answer is -1.
  • aaa is the smallest string with a repeated run. The count for a at k = 1 is 3, so the answer is 1.
  • aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa (50 letters) has one run of length 50. The count at k = 48 is 3, so the answer is 48.
  • abababababab alternates letters, so each run has length 1. The answer is 1 because a and b each occur six times.
  • aabbcc has three runs of length 2 for three letters. Each letter occurs once at k = 2, so the answer is -1.
  • aaabaaaa has runs of 3, 1, and 4 for letter a. At k = 2 the count is 2 + 1 + 3 = 6, and at k = 3 it is 1 + 0 + 2 = 3, so the answer is 3.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Find Longest Special Substring That Occurs Thrice I, with how to answer them.

Unlock the follow-ups

Find Longest Special Substring That Occurs Thrice I FAQ

What is the time complexity of Longest Special Substring Thrice I?

The optimal run-length solution runs in O(n log n) time, where n is the length of the string. The brute force that checks every substring runs in O(n^4) time. The sorting of run lengths is the only step that costs more than a linear scan.

Why use run-length grouping for Longest Special Substring Thrice I?

A special substring is made of one repeated letter, so it always sits inside one run. Grouping runs turns a search over all substrings into a count over a few numbers per letter. The top three runs per letter decide the answer.

Can Longest Special Substring Thrice I be solved in O(1) extra space?

Yes, if you track the top three run lengths for each letter while scanning. That needs 26 letters times three integers, which is a fixed amount of memory. The string itself is the input and does not count as extra space.

Why does the answer start at -1 and not at 0?

The problem asks for -1 when no special substring occurs three times. Starting at 0 would turn that case into a wrong answer of 0. Starting at -1 keeps the no-match case correct without a special branch.

Why does the sliding window pattern fit this problem?

The window grows while the next character matches the first character of the window, and it closes when the letter changes. Each closed window is one maximal run. The window idea finds the runs in a single left-to-right pass.

Asked at

See which companies ask this — Pro

Practise it