#3303

Find the Occurrence of First Almost Equal Substring

Hard
StringString MatchingSliding WindowTwo Pointers
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal approach uses a sliding window technique to maintain a count of character differences between the current substring of `s` and `pattern`. This allows us to efficiently check each substring without needing to re-evaluate characters we've already checked.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to count character differences and a sliding window of size equal to the length of `pattern`.
  2. 2Step 2: Iterate through the first `m` characters of `s` to set up the initial difference count.
  3. 3Step 3: Slide the window across `s`, updating the difference count by removing the character that is sliding out and adding the character that is sliding in.
  4. 4Step 4: If the difference count is 1 or less at any point, return the starting index of that window.
solution.py16 lines
1def findAlmostEqualSubstring(s, pattern):
2    n, m = len(s), len(pattern)
3    diff_count = 0
4    for i in range(m):
5        if s[i] != pattern[i]:
6            diff_count += 1
7    if diff_count <= 1:
8        return 0
9    for i in range(m, n):
10        if s[i] != pattern[i - m]:
11            diff_count += 1
12        if s[i - m] != pattern[0]:
13            diff_count -= 1
14        if diff_count <= 1:
15            return i - m + 1
16    return -1

Complexity note: The time complexity is O(n) because we only make a single pass through `s`, maintaining a count of differences without needing to re-evaluate the entire substring each time.

  • 1Understanding the concept of character differences is crucial for solving substring problems.
  • 2Using a sliding window approach can significantly reduce time complexity.

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