Taro Logo

Longest Word in Dictionary through Deleting

#3 Most AskedMedium
0 views
Topics:
ArraysStringsTwo Pointers

Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

Example 1:

Input: s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
Output: "apple"

Example 2:

Input: s = "abpcplea", dictionary = ["a","b","c"]
Output: "a"

Constraints:

  • 1 <= s.length <= 1000
  • 1 <= dictionary.length <= 1000
  • 1 <= dictionary[i].length <= 1000
  • s and dictionary[i] consist of lowercase English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the length of string `s` and the number and lengths of strings in the `dictionary` array?
  2. What character set should we expect in `s` and the `dictionary` (e.g., only lowercase English letters, or could there be uppercase letters, spaces, or special characters)?
  3. If multiple valid words in the dictionary share the exact same maximum length and are both formed by deleting characters from `s`, how should we handle them beyond lexicographical order?
  4. Can the `dictionary` contain duplicate strings, and if so, should they be deduplicated or processed normally?
  5. What should be returned if the `dictionary` is empty, or if no string in the `dictionary` can be formed by deleting characters from `s`?

Brute Force Solution

Approach

The brute force approach to finding the longest hidden word involves checking every single candidate word from the given list. For each candidate, we determine if it can be formed by crossing out zero or more letters from the main string, and finally select the best match based on length and alphabetical order.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the list of candidate words provided.
  2. Pick the first candidate word from the list to test.
  3. Check if you can spell this candidate word using only the letters available in the main string, making sure you use the letters in the exact order they appear and without rearranging them.
  4. If the candidate word can be spelled out from the main string, save it as a potential winning match.
  5. Move on to the next candidate word on the list and repeat the spelling check process.
  6. Continue doing this for every single word in the list until all candidates have been checked.
  7. Compare all the candidate words that successfully matched against the main string.
  8. Choose the longest one from those successful matches.
  9. If there is a tie where multiple successful words share the exact same longest length, pick the one that comes first in alphabetical order.

Code Implementation

def find_longest_word(main_string, candidate_words):
    winning_match = ""

    # Iterate through each candidate to see if it can be formed by deleting letters from the main string
    for candidate_word in candidate_words:
        main_index = 0
        candidate_index = 0
        
        while main_index < len(main_string) and candidate_index < len(candidate_word):
            if main_string[main_index] == candidate_word[candidate_index]:
                candidate_index += 1
            main_index += 1

        # Check if the entire candidate word was successfully matched in order
        if candidate_index == len(candidate_word):
            if len(candidate_word) > len(winning_match):
                winning_match = candidate_word
            elif len(candidate_word) == len(winning_match) and candidate_word < winning_match:
                winning_match = candidate_word

    # Return the best match found according to length and lexicographical priority
    return winning_match

Big(O) Analysis

Time Complexity
O(d * s) – To analyze the time complexity, let d be the number of words in the dictionary and s be the average length of a word, while n represents the length of the main string. For each of the d candidate words, we iterate through its characters to check if it is a subsequence of the main string, an operation that takes up to O(n) time per word. This requires comparing characters across the main string and the candidate word, resulting in a total of approximately d * s operations in the worst case. Simplifying this evaluation across all candidates gives a total runtime complexity of O(d * n).
Space Complexity
O(1) – The algorithm only requires a few primitive variables to track the current winning word, its length, and loop indices during the iteration. Since no dynamic data structures, recursion stacks, or auxiliary arrays are created to store the candidates or match results, the extra memory usage remains constant regardless of the input size. Therefore, the auxiliary space complexity is O(1).

Optimal Solution

Approach

The optimal strategy is to evaluate each word from a given collection to see if it can be formed by carefully removing certain letters from a base string, while keeping the remaining letters in their original order. By systematically comparing every candidate word against our base string and keeping track of the best match found so far based on length and alphabetical order, we can efficiently find the correct answer.

Here's how the algorithm would work step-by-step:

  1. Go through the collection of candidate words one by one.
  2. For each candidate word, check if it can be spelled out by walking through the base string and picking matching letters in the exact order they appear.
  3. If a candidate word cannot be formed from the base string, ignore it and move on to the next one.
  4. If a candidate word successfully matches, compare it against the current best match you have saved.
  5. If the new matching word is longer than your current best match, update your best match to be this new word.
  6. If the new matching word is the exact same length as your current best match, compare them alphabetically and keep the one that comes first.
  7. Continue this comparison process for every word in the collection until none are left, and then reveal your final saved word as the winning answer.

Code Implementation

def find_longest_word(base_string, dictionary_words):
    longest_valid_word = ""

    # We sort the dictionary to ensure alphabetical precedence for words of equal length.
    sorted_dictionary = sorted(dictionary_words)

    for candidate_word in sorted_dictionary:
        base_string_index = 0
        candidate_index = 0

        while base_string_index < len(base_string) and candidate_index < len(candidate_word):
            if base_string[base_string_index] == candidate_word[candidate_index]:
                candidate_index += 1
            base_string_index += 1

        # A word is valid only if all its characters were matched sequentially.
        if candidate_index == len(candidate_word):
            # We only update if the new word strictly exceeds the current length due to sorting.
            if len(candidate_word) > len(longest_valid_word):
                longest_valid_word = candidate_word

    return longest_valid_word

Big(O) Analysis

Time Complexity
O(n * k) – To analyze the time complexity, let n be the number of words in the collection and k be the maximum length of a word and the base string. For each of the n candidate words, we must iterate through the characters of the base string of length k to verify if it is a valid subsequence. Comparing a candidate word against the current best match takes proportional time to the word's length, bounded by k. This leads to approximately n * k total operations across all candidate words, which simplifies to O(n * k).
Space Complexity
O(1) – To determine the longest valid word, the algorithm only allocates a few primitive variables such as string references and indices to track the current best match and iterate through the inputs. No auxiliary data structures like hash maps or temporary lists scale with the number or length of the candidate words. Therefore, the extra memory usage remains constant regardless of the input size, resulting in an optimal auxiliary space complexity.

Edge Cases

Empty string s or empty dictionary array
How to Handle:
Return an empty string immediately since no valid word can ever be formed.
Dictionary contains strings longer than the source string s
How to Handle:
The subsequence check naturally returns false when a dictionary word exceeds the length of s.
Multiple words in the dictionary are valid and have the exact same maximum length
How to Handle:
Pre-sorting the dictionary lexicographically or tracking the best match alphabetically ensures we return the smallest lexicographical result.
No words in the dictionary can be formed by deleting characters from s
How to Handle:
The result variable remains empty, and the function correctly returns an empty string.
Dictionary contains duplicate strings
How to Handle:
Duplicate words are processed identically and safely without affecting correctness, though sorting handles them adjacent to each other.
Source string s and dictionary words consist of special characters, numbers, or mixed casing
How to Handle:
Standard character-by-character comparison handles any valid Unicode characters as long as exact equality is checked.
Extremely large dictionary with very long strings
How to Handle:
Iterating through the dictionary and performing linear-time subsequence checks ensures memory efficiency without recursion stack overflow.
0/3 completed