#2981

Find Longest Special Substring That Occurs Thrice I

Medium
Hash TableStringBinary SearchSliding WindowCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the fact that special substrings consist of repeated characters. We can count the lengths of consecutive characters and then check how many times each length appears. This reduces the number of checks significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Traverse the string and count consecutive characters, storing their lengths in a list.
  2. 2Step 2: Use a dictionary to count how many times each length appears.
  3. 3Step 3: Iterate through the dictionary to find the maximum length that appears at least three times.
  4. 4Step 4: Return the maximum length found, or -1 if none exists.
solution.py17 lines
1def longest_special_substring(s):
2    count = {}
3    n = len(s)
4    i = 0
5    while i < n:
6        char = s[i]
7        length = 0
8        while i < n and s[i] == char:
9            length += 1
10            i += 1
11        if length > 0:
12            count[length] = count.get(length, 0) + 1
13    max_length = -1
14    for length, freq in count.items():
15        if freq >= 3:
16            max_length = max(max_length, length)
17    return max_length

Complexity note: The time complexity is O(n) because we traverse the string once to count lengths of special substrings. The space complexity is O(n) due to the dictionary storing counts of lengths.

  • 1Special substrings are formed by consecutive identical characters.
  • 2Using a dictionary to count occurrences can significantly reduce checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.