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: 0
💡 Note: The substring "hel" starting at index 0 differs from "ell" by only 1 character (h vs e at position 0), so it's almost equal and is the first valid match.

Constraints

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

Visualization

Tap to expand
Find First Almost Equal Substring INPUT String s: l e e t c o d e 0 1 2 3 4 5 6 7 Pattern: l e o t c o d e Different char! Input Values s = "leetcode" pattern = "leotcode" Almost Equal: Differ by at most 1 character ALGORITHM STEPS 1 Start at index 0 Compare substring s[0:8] 2 Count differences Track mismatch count 3 Early termination Stop if diff > 1 4 Check result Return if diff <= 1 Comparison at index 0: s[0:8]: l e e t c o d e pattern: l e o t c o d e match: OK OK X OK OK OK OK Differences: 1 (e vs o) 1 <= 1, Almost Equal! FINAL RESULT Found at starting index: 0 Matching substring: "leetcode" Almost equals pattern "leotcode" Verification: Position 2: 'e' vs 'o' Only 1 difference - OK! Key Insight: Early Termination Optimization: Stop comparing as soon as mismatch count exceeds 1. This avoids unnecessary comparisons and improves average-case performance significantly. Time: O(n * m) worst case, but often much faster due to early termination. TutorialsPoint - Find the Occurrence of First Almost Equal Substring | Early Termination Optimization
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