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
- 57 lines of Python from the credited upstream file word-squares-ii.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit 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 4import collections5 6 78class Solution(object):9 def wordSquares(self, words):10 """11 :type words: List[str]12 :rtype: List[List[str]]13 """14 words.sort()15 lookup = collections.defaultdict(list)16 for i, w in enumerate(words):17 lookup[w[0]].append(i)18 lookup[w[0], w[3]].append(i)19 result = []20 for i in xrange(len(words)):21 for j in lookup[words[i][0]]:22 if j == i:23 continue24 for k in lookup[words[i][3]]:25 if k in (i, j):26 continue27 for l in lookup[words[j][3], words[k][3]]:28 if l in (i, j, k):29 continue30 result.append([words[i], words[j], words[k], words[l]])31 return result32 33 34353637class Solution2(object):38 def wordSquares(self, words):39 """40 :type words: List[str]41 :rtype: List[List[str]]42 """43 words.sort()44 result = []45 for i in xrange(len(words)):46 for j in xrange(len(words)):47 if j == i or words[j][0] != words[i][0]:48 continue49 for k in xrange(len(words)):50 if k in (i, j) or words[k][0] != words[i][3]:51 continue52 for l in xrange(len(words)):53 if l in (i, j, k) or words[l][0] != words[j][3] or words[l][3] != words[k][3]:54 continue55 result.append([words[i], words[j], words[k], words[l]])56 return result57