#524

Longest Word in Dictionary through Deleting

Medium
ArrayTwo PointersStringSorting
LeetCode ↗

Approaches

💡

Intuition

Time Space

The brute force approach checks every word in the dictionary to see if it can be formed by deleting characters from the string s. This method is straightforward but inefficient, as it involves checking each word individually.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to store the longest valid word found.
  2. 2Step 2: For each word in the dictionary, check if it can be formed from s by deleting characters.
  3. 3Step 3: If a word can be formed and is longer than the current longest, update the longest word. If it's the same length but lexicographically smaller, also update.
solution.py11 lines
1def can_form(word, s):
2    it = iter(s)
3    return all(char in it for char in word)
4
5def longest_word(s, dictionary):
6    longest = ""
7    for word in dictionary:
8        if can_form(word, s):
9            if (len(word) > len(longest)) or (len(word) == len(longest) and word < longest):
10                longest = word
11    return longest

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.