1
1
var letterCombinations = function ( digits ) {
2
+ // if digits is empty return []
2
3
if ( digits == "" ) { return [ ] }
4
+ // we create all possible strings a digit might correspond to
5
+ // digit contains number 2-9 so we keep index 0 and 1 as 0
3
6
let k = [ 0 , 0 , "abc" , "def" , "ghi" , "jkl" , "mno" , "pqrs" , "tuv" , "wxyz" ]
7
+ // we convert first digit to number
4
8
let m = Number ( digits [ 0 ] )
9
+ // we split the corresponding string to alphabets
10
+ // and it will store all output
5
11
let a = k [ m ] . split ( "" )
6
12
let [ p , n ] = [ [ ] , [ ] ]
13
+ // we loop over all digits from index 1 to last index
7
14
for ( let i = 1 ; i < digits . length ; i ++ ) {
15
+ // p will store all possible alphabets for current digit
8
16
p = k [ digits [ i ] ] . split ( "" )
17
+ // n will store all the possible combinations made for that digit
9
18
n = [ ]
19
+ // all possible combinations for given digit are are p.length*a.length
10
20
for ( let j = 0 ; j < p . length * a . length ; j ++ ) {
21
+ // Math.floor(j/p.length) this let us stay in range of index 0-a.length-1
22
+ // j%p.length this let us stay in range of index 0-p.length-1
23
+ // thus going over all possible combination for all given a and p indices
11
24
n . push ( a [ Math . floor ( j / p . length ) ] + p [ j % p . length ] )
12
25
}
26
+ // we update the array a will all current possiblities
13
27
a = n
14
28
}
29
+ // we return all possible combinations
15
30
return a
16
- } ;
31
+ } ;