Approach
Sorting and greedy selection
For Word Squares II, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 66 lines of C++ from the credited upstream file word-squares-ii.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 9 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 vector<vector<string>> wordSquares(vector<string>& words) {8 ranges::sort(words);9 unordered_map<int, vector<int>> lookup;10 for (int i = 0; i < size(words); ++i) {11 lookup[words[i][0] - 'a'].emplace_back(i);12 lookup[(words[i][0] - 'a') + (words[i][3] - 'a' + 1) * 27].emplace_back(i);13 }14 vector<vector<string>> result;15 for (int i = 0; i < size(words); ++i) {16 for (const auto& j : lookup[words[i][0] - 'a']) {17 if (j == i) {18 continue;19 }20 for (const auto& k : lookup[words[i][3] - 'a']) {21 if (k == i || k == j) {22 continue;23 }24 for (const auto& l : lookup[(words[j][3] - 'a') + (words[k][3] - 'a' + 1) * 27]) {25 if (l == i || l == j || l == k) {26 continue;27 }28 result.push_back({words[i], words[j], words[k], words[l]});29 }30 }31 }32 }33 return result;34 }35};36 37383940class Solution2 {41public:42 vector<vector<string>> wordSquares(vector<string>& words) {43 ranges::sort(words);44 vector<vector<string>> result;45 for (int i = 0; i < size(words); ++i) {46 for (int j = 0; j < size(words); ++j) {47 if (j == i || words[j][0] != words[i][0]) {48 continue;49 }50 for (int k = 0; k < size(words); ++k) {51 if (k == i || k == j || words[k][0] != words[i][3]) {52 continue;53 }54 for (int l = 0; l < size(words); ++l) {55 if (l == i || l == j || l == k || words[l][0] != words[j][3] || words[l][3] != words[k][3]) {56 continue;57 }58 result.push_back({words[i], words[j], words[k], words[l]});59 }60 }61 }62 }63 return result;64 }65};66