Letter Tile Possibilities LeetCode solution in JavaScript

1
//""This solution isn`t the best way but it`s simple""
2
var numTilePossibilities = function (tiles) {
3
return search(tiles);
4
};
5
// this function takes a state and check if it`s valid or !
6
// valid state is not null state and unique
7
// e.g ["","A","A"]=>is not valid state because is has null state and repeated
8
// values by contrast ["A"] is valid state
9
// !!state below is to check if state not null
10
const isValidState = (state = "", res = []) => !!state && !res.includes(state);
11
// this function permutes tiles by backtracking
12
const search = (tiles = "", state = "", result = []) => {
13
if (isValidState(state, result))
14
//check if the current state valid
15
result.push(state);
16
//loop through tiles and every time you push letter to state
17
// the remaining tiles will decreased by one
18
/**
19
* ---e.g--
20
* level 1 tiles=AAB state=""
21
* it will loop through the tiles ;
22
* now I am in index 0 push tiles[0] to state now state=A
23
* by making this operation number of option tiles will be
24
* decreased to newTiles="AB"
25
* ...
26
* ..
27
* .
28
* */
29
for (let i = 0; i < tiles.length; i++) {
30
state += tiles[i];
31
const newTiles = tiles.substring(0, i) + tiles.substring(i + 1);
32
search(newTiles, state, result);
33
state = state.slice(0, state.length - 1);
34
}
35
return result.length;
36
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0