Find the Lexicographically Smallest Valid Sequence - Problem

You are given two strings word1 and word2.

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.

A sequence of indices seq is called valid if:

  • The indices are sorted in ascending order.
  • Concatenating the characters at these indices in word1 in the same order results in a string that is almost equal to word2.

Return an array of size word2.length representing the lexicographically smallest valid sequence of indices. If no such sequence of indices exists, return an empty array.

Note that the answer must represent the lexicographically smallest array, not the corresponding string formed by those indices.

Input & Output

Example 1 — Basic Case
$ Input: word1 = "vsum", word2 = "um"
Output: [2,3]
💡 Note: We can pick indices [2,3] to get "um" which exactly matches word2. This is the lexicographically smallest valid sequence.
Example 2 — One Character Difference
$ Input: word1 = "hello", word2 = "eo"
Output: [1,4]
💡 Note: Pick indices [1,4] to get "eo" which exactly matches word2. Other combinations like [0,4] would give "ho" requiring one change.
Example 3 — No Valid Sequence
$ Input: word1 = "abc", word2 = "def"
Output: []
💡 Note: No sequence of indices can form a string almost equal to "def" since we'd need to change all characters.

Constraints

  • 1 ≤ word1.length, word2.length ≤ 3 × 103
  • word1 and word2 consist only of lowercase English letters.

Visualization

Tap to expand
Lexicographically Smallest Valid Sequence INPUT word1 = "vsum" v idx 0 s idx 1 u idx 2 m idx 3 word2 = "um" u pos 0 m pos 1 Find smallest indices to form "almost equal" string (at most 1 char different) ALGORITHM STEPS 1 Precompute Suffix For each i, can we match suffix of word2 from i? 2 Greedy Selection Pick smallest index first if valid path exists 3 Lookahead Check Verify remaining chars can still be matched 4 Build Result Track one mismatch allowed for "almost equal" Matching Process: i=2: word1[2]='u' == 'u' OK i=3: word1[3]='m' == 'm' OK FINAL RESULT Valid Sequence Found [2, 3] Selected indices: 2 and 3 Verification: word1[2] = 'u' --> 'u' OK word1[3] = 'm' --> 'm' OK Result: "um" exact match! Lexicographically Smallest: [2,3] Key Insight: The greedy approach with lookahead ensures we pick the smallest index at each step while guaranteeing a valid sequence exists. Precomputing suffix matches allows O(1) lookahead checks. "Almost equal" means at most one character can differ, giving flexibility in matching. TutorialsPoint - Find the Lexicographically Smallest Valid Sequence | Greedy with Lookahead
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
856 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