#2982

Find Longest Special Substring That Occurs Thrice II

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)

This approach uses a single pass to determine the lengths of special substrings and a hash map to count their occurrences efficiently. This reduces the time complexity significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Traverse the string to find lengths of contiguous special substrings and store them in an array.
  2. 2Step 2: Use a hash map to count how many times each special substring length appears.
  3. 3Step 3: Check the hash map for lengths that appear at least three times and return the maximum length found.
solution.py27 lines
1# Full working Python code
2
3def longest_special_substring(s):
4    from collections import defaultdict
5    n = len(s)
6    lengths = []
7    count_map = defaultdict(int)
8
9    # Step 1: Find lengths of special substrings
10    current_length = 1
11    for i in range(1, n):
12        if s[i] == s[i - 1]:
13            current_length += 1
14        else:
15            lengths.append(current_length)
16            count_map[current_length] += 1
17            current_length = 1
18    lengths.append(current_length)
19    count_map[current_length] += 1
20
21    # Step 2: Find the maximum length that occurs at least thrice
22    max_length = -1
23    for length, count in count_map.items():
24        if count >= 3:
25            max_length = max(max_length, length)
26
27    return max_length

Complexity note: The time complexity is O(n) because we only traverse the string once to gather lengths of special substrings, and the space complexity is O(n) due to the hash map used for counting.

  • 1Special substrings are contiguous sequences of the same character.
  • 2Using a hash map allows for efficient counting of substring lengths.

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