Skip to content

Commit 51ac1cc

Browse files
committed
Add solution #425
1 parent 592944f commit 51ac1cc

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,7 @@
413413
422|[Valid Word Square](./solutions/0422-valid-word-square.js)|Easy|
414414
423|[Reconstruct Original Digits from English](./solutions/0423-reconstruct-original-digits-from-english.js)|Medium|
415415
424|[Longest Repeating Character Replacement](./solutions/0424-longest-repeating-character-replacement.js)|Medium|
416+
425|[Word Squares](./solutions/0425-word-squares.js)|Hard|
416417
427|[Construct Quad Tree](./solutions/0427-construct-quad-tree.js)|Medium|
417418
429|[N-ary Tree Level Order Traversal](./solutions/0429-n-ary-tree-level-order-traversal.js)|Medium|
418419
430|[Flatten a Multilevel Doubly Linked List](./solutions/0430-flatten-a-multilevel-doubly-linked-list.js)|Medium|

solutions/0425-word-squares.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* 425. Word Squares
3+
* https://leetcode.com/problems/word-squares/
4+
* Difficulty: Hard
5+
*
6+
* Given an array of unique strings words, return all the word squares you can build from
7+
* words. The same word from words can be used multiple times. You can return the answer
8+
* in any order.
9+
*
10+
* A sequence of strings forms a valid word square if the kth row and column read the same
11+
* string, where 0 <= k < max(numRows, numColumns).
12+
*
13+
* - For example, the word sequence ["ball","area","lead","lady"] forms a word square because
14+
* each word reads the same both horizontally and vertically.
15+
*/
16+
17+
/**
18+
* @param {string[]} words
19+
* @return {string[][]}
20+
*/
21+
var wordSquares = function(words) {
22+
const result = [];
23+
const prefixMap = new Map();
24+
const wordLength = words[0].length;
25+
26+
for (const word of words) {
27+
for (let i = 0; i < word.length; i++) {
28+
const prefix = word.slice(0, i);
29+
if (!prefixMap.has(prefix)) {
30+
prefixMap.set(prefix, []);
31+
}
32+
prefixMap.get(prefix).push(word);
33+
}
34+
}
35+
36+
function buildSquare(currentSquare) {
37+
if (currentSquare.length === wordLength) {
38+
result.push([...currentSquare]);
39+
return;
40+
}
41+
42+
const prefix = currentSquare
43+
.map(word => word[currentSquare.length])
44+
.join('');
45+
46+
const candidates = prefixMap.get(prefix) || [];
47+
for (const candidate of candidates) {
48+
currentSquare.push(candidate);
49+
buildSquare(currentSquare);
50+
currentSquare.pop();
51+
}
52+
}
53+
54+
for (const word of words) {
55+
buildSquare([word]);
56+
}
57+
58+
return result;
59+
};

0 commit comments

Comments
 (0)