← Home

524. Longest Word in Dictionary through Deleting

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
524

The trick here is to name the state correctly, then let the implementation follow. For 524. Longest Word in Dictionary through Deleting, the solution in this repository is mainly a greedy solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

The notes already sitting in the source point us in the right direction:

  • Approach 1: Recursive Brute Force
  • time: O(2^n), space: O(2^n)
  • Approach 2: Iterative Brute Force
  • time: O(2^n), space: O(2^n)

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are findLongestWord, isSubsequence.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(nx), space: O(x)
  • Space: O(logn)

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Approach 1: Recursive Brute Force
02//time: O(2^n), space: O(2^n)
03
04//Approach 2: Iterative Brute Force
05//time: O(2^n), space: O(2^n)
06
07//Approach 3: Sorting and Checking Subsequence
08//Runtime: 88 ms, faster than 64.35% of C++ online submissions for Longest Word in Dictionary through Deleting.
09//Memory Usage: 15.5 MB, less than 100.00% of C++ online submissions for Longest Word in Dictionary through Deleting.
10//time: O((nlogn + n)*x), x refers to average string length
11//space: O(logn)
12class Solution {
13public:
14    string findLongestWord(string s, vector<string>& d) {
15        sort(d.begin(), d.end(), [](const string& a, const string& b){
16            return (a.size() == b.size()) ? a < b : a.size() > b.size();
17        });
18        
19        for(string& word : d){
20            int wi = 0, si = 0;
21            while(wi < word.size() && si < s.size()){
22                if(word[wi] == s[si]){
23                    wi++;
24                    si++;
25                }else{
26                    si++;
27                }
28            }
29            // cout << wi << "/" << word.size() << " " << si << "/" << s.size() << endl;
30            if(wi == word.size()){
31                return word;
32            }
33        }
34        
35        return "";
36    }
37};
38
39//Approach 4: Without Sorting
40//Runtime: 92 ms, faster than 44.98% of C++ online submissions for Longest Word in Dictionary through Deleting.
41//Memory Usage: 23 MB, less than 7.69% of C++ online submissions for Longest Word in Dictionary through Deleting.
42//time: O(nx), space: O(x)
43class Solution {
44public:
45    bool isSubsequence(string sub, string super){
46        //check whether sub is a substring of super
47        int i = 0, j = 0;
48        while(i < sub.size() && j < super.size()){
49            if(sub[i] == super[j]){
50                i++;
51                j++;
52            }else{
53                j++;
54            }
55        }
56        return i == sub.size();
57    };
58    
59    string findLongestWord(string s, vector<string>& d) {
60        string ans = "";
61        for(string& word : d){
62            if(word.size() > ans.size() || 
63               (word.size() == ans.size() && word < ans)){
64                if(isSubsequence(word, s)){
65                    ans = word;
66                }
67            }
68        }
69        return ans;
70    }
71};

Cost

Complexity

Time
O(nx), space: O(x)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(logn)
Auxiliary state plus the answer structure where the problem requires one.