This problem looks busy at first, but the accepted solution is built around one steady invariant. For 318. Maximum Product of Word Lengths, the solution in this repository is mainly a bit manipulation solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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: bit manipulation.
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are maxProduct, hashs.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- 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:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
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(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 100 ms, faster than 28.36% of C++ online submissions for Maximum Product of Word Lengths.
02//Memory Usage: 10.8 MB, less than 100.00% of C++ online submissions for Maximum Product of Word Lengths.
03class Solution {
04public:
05 int maxProduct(vector<string>& words) {
06 int N = words.size();
07 vector<int> hashs(N);
08 int ans = 0;
09
10 //convert them into int(bit representation)
11 for(int i = 0; i < N; i++){
12 for(char c : words[i]){
13 hashs[i] |= (1 << (c-'a'));
14 }
15 }
16
17 for(int i = 0; i < N; i++){
18 vector<int>::iterator it = hashs.begin()+i;
19 while(it != hashs.end()){
20 it = find_if(it+1, hashs.end(),
21 [&hashs, i](const int& e){
22 return ((hashs[i] & e) == 0);
23 });
24 //if we can find hashs[j] s.t. hashs[i] & hashs[i] is 0
25 if(it != hashs.end()){
26 ans = max(ans, (int)words[i].size() * (int)words[it-hashs.begin()].size());
27 }
28 }
29 }
30
31 return ans;
32 }
33};
Cost