1
+ /**
2
+ * Given a string, write a function to check if it is a permutation of a palindrome.
3
+ * A palindrome is a word or phrase that is the same forwards and backwards.
4
+ * A permutation is a rearrangement of letters. The palindrome does not need to be
5
+ * limited to just dictionary words.
6
+ * Better explanation:
7
+ * https://codingbootcampguides.com/coding-interviews-solving-the-palindrome-permutation-problem-in-javascript/
8
+ */
9
+ function isPalindromePermutation ( text ) {
10
+ const dictionary = { } ;
11
+ const textNonSpaces = text . replaceAll ( ' ' , '' ) ;
12
+
13
+ for ( let latter of textNonSpaces ) {
14
+ if ( latter in dictionary ) {
15
+ dictionary [ latter ] ++ ;
16
+ } else {
17
+ dictionary [ latter ] = 1
18
+ }
19
+ }
20
+
21
+ // a single odd is allow because is the center of the palindrome
22
+ let foundOdd = false ;
23
+
24
+ for ( const letter of Object . keys ( dictionary ) ) {
25
+ if ( isOdd ( dictionary [ letter ] ) ) {
26
+ if ( foundOdd ) return false ;
27
+
28
+ foundOdd = true ;
29
+ }
30
+ }
31
+
32
+ return true ;
33
+ }
34
+
35
+ function isPalindromePermutationRecurse ( text ) {
36
+ const dictionary = createDictionaryRecurse ( text . replace ( ' ' , '' ) , 0 , { } )
37
+ return isAllEvenExceptOneRecurse ( Object . values ( dictionary ) , 0 , false , true ) ;
38
+ }
39
+
40
+ function createDictionaryRecurse ( text , index , result ) {
41
+ debugger ;
42
+ if ( index > text . length - 1 ) return result ;
43
+
44
+ const word = text [ index ] ;
45
+
46
+ if ( word in result ) {
47
+ result [ word ] ++ ;
48
+ } else {
49
+ result [ word ] = 1 ;
50
+ }
51
+
52
+ return createDictionaryRecurse ( text , index + 1 , result ) ;
53
+ }
54
+
55
+ function isAllEvenExceptOneRecurse ( counts , index , foundOdd , result ) {
56
+ debugger ;
57
+ if ( index > counts . length - 1 ) return result ;
58
+ const count = counts [ index ] ;
59
+
60
+ if ( isOdd ( count ) ) {
61
+ if ( foundOdd ) return false ;
62
+
63
+ return isAllEvenExceptOneRecurse ( counts , index + 1 , true , true ) ;
64
+ } else {
65
+ return isAllEvenExceptOneRecurse ( counts , index + 1 , foundOdd , true ) ;
66
+ }
67
+ }
68
+
69
+ function isOdd ( number ) {
70
+ return ! ( number % 2 == 0 ) ;
71
+ }
72
+
73
+ module . exports = {
74
+ isPalindromePermutation,
75
+ isPalindromePermutationRecurse
76
+ }
0 commit comments