Find the Occurrence of First Almost Equal Substring - Problem

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.

Input & Output

Example 1 — Basic Almost Equal
$ Input: s = "leetcode", pattern = "leotcode"
Output: 0
💡 Note: The substring "leetcode" starting at index 0 differs from "leotcode" by only 1 character (e vs o at position 2), so it's almost equal.
Example 2 — No Match Found
$ Input: s = "abcdef", pattern = "xyz"
Output: -1
💡 Note: No substring of length 3 in "abcdef" is almost equal to "xyz" (all would have 3 mismatches).
Example 3 — Exact Match
$ Input: s = "hello", pattern = "ell"
Output: 1
💡 Note: The substring "ell" starting at index 1 is exactly equal to pattern "ell" (0 differences ≤ 1).

Constraints

  • 1 ≤ s.length, pattern.length ≤ 105
  • s and pattern consist of lowercase English letters

Visualization

Tap to expand
Find Almost Equal SubstringInput: s = "leetcode", pattern = "leotcode"String s:leetcodePattern:leotcodeOnly 1 character differs (e vs o)Almost equal! Return index 0
Understanding the Visualization
1
Input
String s and pattern to match
2
Process
Check each substring and count differences
3
Output
Return index of first almost equal substring
Key Takeaway
🎯 Key Insight: Count character differences - if ≤1, the substring is almost equal
Asked in
Google 15 Meta 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen