We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find the Occurrence of First Almost Equal Substring

Difficulty: Hard


Problem Description

You are given two strings s and pattern. A string x is called almost equal to y if you can change at most one character in x to make it identical to y. Return the smallest starting index of a substring in s that is almost equal to pattern. If no such index exists, return -1. A substring is a contiguous non-empty sequence of characters within a string.


Key Insights

  • A substring of s must have the same length as pattern to be considered for comparison.
  • We can iterate through each possible starting index of s where a substring of the same length as pattern can exist.
  • We need to count the number of character mismatches between the substring and pattern.
  • If the number of mismatches is at most 1, we have found a valid starting index.

Space and Time Complexity

Time Complexity: O(n * m), where n is the length of s and m is the length of pattern.
Space Complexity: O(1), as we are using a constant amount of space for counters.


Solution

To solve the problem, we will:

  1. Loop through each starting index i in s where a substring of length equal to pattern can start.
  2. For each starting index, extract the substring from s and compare it to pattern.
  3. Count the number of positions where the characters differ.
  4. If the number of differences is less than or equal to 1, return the starting index i.
  5. If no valid index is found after checking all possible substrings, return -1.

The main data structure used here is a simple string, and we rely on basic iteration and comparison.


Code Solutions

def find_first_almost_equal(s: str, pattern: str) -> int:
    len_s = len(s)
    len_pattern = len(pattern)

    for i in range(len_s - len_pattern + 1):
        substring = s[i:i + len_pattern]
        mismatch_count = sum(1 for j in range(len_pattern) if substring[j] != pattern[j])

        if mismatch_count <= 1:
            return i

    return -1
← Back to All Questions