Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Backtracking/LetterCombos.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
function letterCombinations(digits) {
if (digits === '') {
// base case
return []
}

const dic = {
2: 'abc',
3: 'def',
4: 'ghi',
5: 'jkl',
6: 'mno',
7: 'pqrs',
8: 'tuv',
9: 'wxyz'
}

const res = [] // letter combinations to return
const combo = []

function backtrack(i) {
if (i === digits.length) {
res.push(combo.join(''))
return
}

for (const c of dic[digits[i]]) {
combo.push(c)
backtrack(i + 1)
combo.pop()
}
}

backtrack(0)
return res
}

export { letterCombinations }
34 changes: 34 additions & 0 deletions Backtracking/WordSearch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
function exist(board, word) {
const ROWS = board.length;
const COLS = board[0].length;
const visited = new Set();

function backtrack(row, col, idx) {
if (idx === word.length) {
return true;
}

if (!(0 <= row && row < ROWS && 0 <= col && col < COLS && !visited.has(`${row},${col}`)
&& idx < word.length && board[row][col] === word[idx])) {
return false;
}

visited.add(`${row},${col}`);
const res = (backtrack(row - 1, col, idx + 1) || backtrack(row + 1, col, idx + 1) ||
backtrack(row, col - 1, idx + 1) || backtrack(row, col + 1, idx + 1));
visited.delete(`${row},${col}`);
return res;
}

for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
if (board[row][col] === word[0] && backtrack(row, col, 0)) {
return true;
}
}
}

return false;
}

export {exist}
18 changes: 18 additions & 0 deletions Backtracking/tests/LetterCombos.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { letterCombinations } from '../LetterCombos'

describe('LetterCombinations', () => {
it('Letter Combinations of 23', () => {
const res = letterCombinations('23')
expect(res).toEqual(['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf'])
})

it('Letter Combinations of empty string', () => {
const res = letterCombinations('')
expect(res).toEqual([])
})

it('Letter Combinations of 2', () => {
const res = letterCombinations('2')
expect(res).toEqual(['a', 'b', 'c'])
})
})