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
Find Lexicographically Smallest Valid Sequenceword1:vsum0123word2:umSelect indices [2,3] → "um"Almost equal: 0 differences ≤ 1 ✓Lexicographically smallest: [2,3] < any other valid sequenceOutput: [2,3]
Understanding the Visualization
1
Input
Two strings word1 and word2
2
Process
Find indices in word1 that form string almost equal to word2
3
Output
Lexicographically smallest valid sequence or empty array
Key Takeaway
🎯 Key Insight: Greedily choose the smallest valid index at each position while ensuring future matches remain possible
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