Skip to content

Commit 8b3e245

Browse files
authored
Space complexity optimization approach
1 parent eadc2e4 commit 8b3e245

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

word-search/kimyoung.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Space Complexity O(m * n + w) approach
12
var exist = function (board, word) {
23
const rowLen = board.length, colLen = board[0].length;
34
let visited = new Set(); // keep track of visited coordinates
@@ -32,3 +33,37 @@ var exist = function (board, word) {
3233

3334
// time - O(m * n * 4^w) traverse through the matrix (m * n) and run dfs on each of the possible paths (4^w) 4 being 4 directions
3435
// space - O(m * n + w)
36+
37+
// Space Complexity O(1) approach
38+
var exist = function (board, word) {
39+
const rowLen = board.length, colLen = board[0].length;
40+
41+
function dfs(row, col, idx) {
42+
if (idx === word.length) return true;
43+
if (row < 0 || col < 0 ||
44+
row >= rowLen || col >= colLen ||
45+
board[row][col] !== word[idx]) return false;
46+
47+
const letter = board[row][col];
48+
board[row][col] = '#'
49+
let result = dfs(row + 1, col, idx + 1) ||
50+
dfs(row - 1, col, idx + 1) ||
51+
dfs(row, col + 1, idx + 1) ||
52+
dfs(row, col - 1, idx + 1);
53+
board[row][col] = letter
54+
55+
return result;
56+
}
57+
58+
for (let row = 0; row < rowLen; row++) {
59+
for (let col = 0; col < colLen; col++) {
60+
if (board[row][col] === word[0] &&
61+
dfs(row, col, 0)) return true;
62+
}
63+
}
64+
65+
return false;
66+
};
67+
68+
// time - O(m * n * 4^w) traverse through the matrix (m * n) and run dfs on each of the possible paths (4^w) 4 being 4 directions
69+
// space - O(1)

0 commit comments

Comments
 (0)