425. Word Squares
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method: Backtracking with Prefix Map
This problem asks for all possible word squares that can be formed from a given list of words. A key property of a word square is that the k-th row and k-th column are identical. This symmetry implies square[i][j] == square[j][i] for all i, j. This structure suggests a search problem where we can build the square row by row, and for each new row, we check if it maintains the word square property with the existing rows.
Solution
Word Squares in Python
import collections
class Solution:
def wordSquares(self, words: list[str]) -> list[list[str]]:
if not words:
return []
n = len(words[0])
# Build a map from prefixes to words
prefix_map = collections.defaultdict(list)
for word in words:
# We need prefixes of length 0 to n-1 for our search.
# word[:i] gives a prefix of length i.
for i in range(n):
prefix_map[word[:i]].append(word)
results = []
def backtrack(current_square):
# If a full square is formed, add it to results
if len(current_square) == n:
results.append(list(current_square))
return
k = len(current_square) # Current row index to fill
# Construct the prefix for the next word
prefix = "".join([word[k] for word in current_square])
# Find candidates with the required prefix and recurse
# prefix_map.get(prefix, []) handles cases where the prefix is not found
for candidate in prefix_map.get(prefix, []):
current_square.append(candidate) # Choose
backtrack(current_square) # Recurse
current_square.pop() # Backtrack
backtrack([])
return results
Word Squares in Java
class Solution {
private int n; // Length of words
private Map<String, List<String>> prefixMap;
private List<List<String>> results;
public List<List<String>> wordSquares(String[] words) {
if (words == null || words.length == 0) {
return new ArrayList<>();
}
this.n = words[0].length();
this.prefixMap = new HashMap<>();
this.results = new ArrayList<>();
// Build a map from prefixes to words
for (String word : words) {
// We need prefixes of length 0 to n-1 for our search.
// word.substring(0, i) gives a prefix of length i.
for (int i = 0; i < n; i++) {
String prefix = word.substring(0, i);
// Add word to the list for this prefix
prefixMap.computeIfAbsent(prefix, k -> new ArrayList<>()).add(word);
}
}
backtrack(new LinkedList<String>());
return results;
}
private void backtrack(LinkedList<String> currentSquare) {
// If a full square is formed, add it to results
if (currentSquare.size() == n) {
results.add(new ArrayList<>(currentSquare));
return;
}
int k = currentSquare.size(); // Current row index to fill
StringBuilder prefixBuilder = new StringBuilder();
// Construct the prefix for the next word
for (String word : currentSquare) {
prefixBuilder.append(word.charAt(k));
}
String prefix = prefixBuilder.toString();
// Find candidates with the required prefix
List<String> candidates = prefixMap.getOrDefault(prefix, new ArrayList<>());
for (String candidate : candidates) {
currentSquare.add(candidate); // Choose
backtrack(currentSquare); // Recurse
currentSquare.removeLast(); // Backtrack
}
}
}
Word Squares in C++
class Solution {
public:
vector<vector<string>> wordSquares(vector<string>& words) {
if (words.empty()) {
return {};
}
n = words[0].length();
// Build a map from prefixes to words
for (const string& word : words) {
// We need prefixes of length 0 to n-1 for our search.
// word.substr(0, i) gives a prefix of length i.
for (int i = 0; i < n; ++i) {
prefixMap[word.substr(0, i)].push_back(word);
}
}
vector<string> currentSquare;
backtrack(currentSquare);
return results;
}
private:
int n;
unordered_map<string, vector<string>> prefixMap;
vector<vector<string>> results;
void backtrack(vector<string>& currentSquare) {
// If a full square is formed, add it to results
if (currentSquare.size() == n) {
results.push_back(currentSquare);
return;
}
int k = currentSquare.size(); // Current row index to fill
string prefix = "";
// Construct the prefix for the next word
for (const string& word : currentSquare) {
prefix += word[k];
}
// Find candidates with the required prefix
// Using .find() is safer than operator[] which might insert an element
if (prefixMap.count(prefix)) {
const vector<string>& candidates = prefixMap.at(prefix);
for (const string& candidate : candidates) {
currentSquare.push_back(candidate); // Choose
backtrack(currentSquare); // Recurse
currentSquare.pop_back(); // Backtrack
}
}
}
};
Word Squares in TypeScript
function wordSquares(words: string[]): string[][] {
if (words.length === 0) {
return [];
}
const n = words[0].length;
const prefixMap = new Map<string, string[]>();
// Build a map from prefixes to words
for (const word of words) {
// We need prefixes of length 0 to n-1 for our search.
// word.substring(0, i) gives a prefix of length i.
for (let i = 0; i < n; i++) {
const prefix = word.substring(0, i);
if (!prefixMap.has(prefix)) {
prefixMap.set(prefix, []);
}
prefixMap.get(prefix)!.push(word);
}
}
const results: string[][] = [];
function backtrack(currentSquare: string[]): void {
// If a full square is formed, add it to results
if (currentSquare.length === n) {
results.push([...currentSquare]); // Add a copy
return;
}
const k = currentSquare.length; // Current row index to fill
let prefix = "";
// Construct the prefix for the next word
for (const word of currentSquare) {
prefix += word[k];
}
// Find candidates with the required prefix and recurse
const candidates = prefixMap.get(prefix) || [];
for (const candidate of candidates) {
currentSquare.push(candidate); // Choose
backtrack(currentSquare); // Recurse
currentSquare.pop(); // Backtrack
}
}
backtrack([]);
return results;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.