Code Interview Note
  • 0. Introduction
  • 1. Basic
    • Python Basic
    • Java Basic
    • Primitive Type
    • Basic Question
    • Number
  • 2. Array and Numbers
    • General
    • TwoSum
    • Buy and Sell Stock
    • SubArray
      • SubArray + HashMap
    • Sliding Window
      • Sliding Window At Most Problem
    • Word Break
    • Passes Problem
    • Majority Element
    • Partition Array
    • Sort Colors
    • Anagram
    • Ugly Number
    • TwoPointer
    • Swipe Line
    • Calculator
    • Sudoku
  • 2.1 String
    • String
    • Palindrome
    • Parentheses
    • Decode String
    • Calculator
    • Abbreviation
  • 3. Linkedlist
    • Dummy Node
    • Double Pointers
  • 4. Stack and Queue
    • General
    • Increase/Decrease Stack
  • 5. Binary Search
    • General
    • BS on result
    • Save the half which has result
    • Rotated Sorted Array
    • Split Array Largest Sum
  • 6. Binary Tree
    • General
    • Path Sum
    • Lowest Common Ancestor
    • BST
    • Convert
    • Traverse
    • Valid Ordered Tree
    • Construct Binary Tree
    • Tree depth and width
    • Vertical Order Traverse
  • 7. Heap
    • Geneal
    • TopK
  • 8. Simulation
    • General
    • Read4
    • Encode Decode
    • LRU/LFU
    • Robot
    • GetRandom O(1)
    • Probability
  • 9. DFS
    • Backtrack
    • General
    • Subset
    • Permutation
    • Combination
  • 10. HashTable
    • General
  • 11. Sort
    • General
  • 12. Recursion
    • General
  • 13. Dynamic Programming
    • Graph
    • General
    • Coordinate
    • Double Sequence
    • Longest Common Subsequence
    • Rolling Array
    • House Robber
    • Backpack
    • Memorization
    • Diagonal
  • 14. BFS
    • General
    • Number of Islands
    • The Maze
  • 15. Graph
    • Shortest Path
    • Undirected Graph
    • Topology Sort
    • Word Ladder
    • Tarjan's Algo
  • 16. Divide & Conquer
    • General
  • 17. UnionFind
    • General
    • Grouping
  • 18. Trie
    • General
    • Word Square
  • 19. Company Summary
    • Oracle
    • Amazon
      • DP
    • Google
    • Hackerrank
    • LinkedIn
  • 20. Design
  • 21. Math
  • Behavior Question
  • Internet
  • OS
Powered by GitBook
On this page
  • 422 Valid Word Square
  • 425 Word Square II

Was this helpful?

  1. 18. Trie

Word Square

422 Valid Word Square

Given a sequence of words, check whether it forms a valid word square.

A sequence of words forms a valid word square if the kth row and column read the exact same string

public boolean validWordSquare(List<String> words) {
   for(int i=0; i<words.size(); i++){
       for(int j=0; j<words.get(i).length(); j++){
           if(j>=words.size() || 
              i>= words.get(j).length() || 
              words.get(i).charAt(j) != words.get(j).charAt(i))
               return false;
       }
   }
    return true;
}

425 Word Square II

Given a set of words (without duplicates), find all word squares you can build from them.

  • Build a trie, record the prefix string list in every node

  • search the word by word square rule

from collections import defaultdict
class TrieNode:
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.prefixList = []

        
class Trie:
    def __init__(self, words):
        self.root = TrieNode()
        for word in words:
            node = self.root
            for c in word:
                node = node.children[c]
                node.prefixList.append(word)
                
    def serachPrefixWord(self, prefix):
        node = self.root
        for c in prefix:
            node = node.children[c]
            
        return node.prefixList
    

class Solution:
    def wordSquares(self, words: List[str]) -> List[List[str]]:
        if not words: return []
        
        self.trie = Trie(words)
        
        self.s = set(words)
        self.ans = []
        
        for word in words:
            square = [word]
            self.backtrack(square, 1)
            
        return self.ans
            
        
    def backtrack(self, square, idx):
        if idx == len(square[0]):
            self.ans.append(square.copy())
            return
        
        # prefix 是利用 square 的 column 建成
        prefix = ''.join(word[idx] for word in square)
        
        # for cand in self.getWords(prefix):
        for cand in self.trie.serachPrefixWord(prefix):
            square.append(cand)
            self.backtrack(square, idx+1)
            square.pop()
        
    
#     def getWords(self, prefix):
#         return [word for word in self.s if word.startswith(prefix)]
PreviousGeneralNext19. Company Summary

Last updated 5 years ago

Was this helpful?