#3557

Find Maximum Number of Non Intersecting Substrings

Medium
Hash TableStringDynamic ProgrammingGreedyHash 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)

We can track the starting and ending indices of valid substrings using a hash map. This allows us to efficiently count non-overlapping substrings.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a map to store the last occurrence of each character.
  2. 2Step 2: Iterate through the string, and for each character, check if a valid substring can be formed.
  3. 3Step 3: Count non-overlapping valid substrings by updating the last used index.
solution.py11 lines
1def maxNonIntersectingSubstrings(word):
2    last = {}
3    count = 0
4    end = -1
5    for i in range(len(word)):
6        if word[i] in last:
7            if i - last[word[i]] >= 4 and last[word[i]] > end:
8                count += 1
9                end = i
10        last[word[i]] = i
11    return count

Complexity note: We traverse the string once, using a hash map for constant time lookups.

  • 1Substrings must be at least 4 characters long.
  • 2Non-overlapping substrings are crucial.

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