KatInterview

Filter Words Expandable to Target String

StringsAuto-graded · 20 test cases
MediumAuto-gradedStringsstringstwo-pointersarrays

Last updated

Determine which words from a dictionary can yield a target string by expanding consecutive duplicate characters in place.

Given a target string target_str and a list of candidate strings word_list, identify all words in word_list that can be expanded to form target_str by duplicating any of their characters zero or more times in place.

A word can expand to target_str if and only if:

  1. It contains the exact same sequence of character runs (consecutive identical characters) in the exact same order as target_str.
  2. For every corresponding run, the length of the run in the candidate word is less than or equal to the length of the run in target_str.

Return a list of all matching words in the order they originally appeared in word_list.

Constraints

  • target_str contains only lowercase English letters ('a'–'z'). Length is between 0 and $10^5$.
  • word_list contains unique candidate strings consisting of lowercase English letters ('a'–'z').
  • Total length of all strings in word_list does not exceed $10^6$.
  • The empty word "" matches target_str if and only if target_str is also "".

Examples

Example 1

Input: find_expandable_words('heellp', ['help', 'hellp', 'heelp', 'heeellp', 'heap'])

Output: ['help', 'hellp', 'heelp']

Example 2

Input: find_expandable_words([''], [''])

Output: []

Hints

Hint 1

Break both the target string and candidate words into run-length encodings (character and run length).

Hint 2

Compare the list of runs character-by-character: characters must match, sequence length must match, and word run lengths cannot exceed target run lengths.

Hint 3

You can compress target_str once at the start to quickly evaluate each candidate word.