Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Find the Lexicographically Smallest Valid Sequence

XPChallenge Points: 20
levelLevel: Medium

You are given two strings: word1 and word2.

We want to find a sequence of indices from word1 (in increasing order) such that the characters picked from these positions form a string that is almost the same as word2.
Two strings are considered almost the same if you can make them identical by changing at most one character in the first string.

Return the lexicographically smallest such sequence of indices (i.e., the earliest positions are preferred).
If no such sequence exists, return an empty list.

Example 1:

Input: word1 = "abcxyz" word2 = "abcy"

Output: [0,1,2,3]

Explanation:

"abcx" differs from "abcy" by one character → valid.

Example 2:

Input: word1 = "zzazb" word2 = "aab"

Output: [1,2,4]

Explanation:

Pick indices → 'z','a','b' Change 'z' → 'a', matches "aab". Lexicographically smallest option.

Example 3:

Input: word1 = "hello" word2 = "world"

Output: []

Explanation:

Even changing one character cannot turn any chosen sequence into "world".

Example 4:

Input: word1 = "aac" word2 = "aac"

Output: [0,1,2]

Explanation:

They already match exactly.

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result