Skip to content

Commit 1df57f2

Browse files
authored
avc278 - 1.04 - Javascript (#59)
Added my solution to the Chapter 1 Problem 4 folder.
1 parent dda338b commit 1df57f2

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. A
2+
// palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters.
3+
// The palindrome does not need to be limited to just dictionary words.
4+
5+
const assert = require("assert");
6+
7+
/**
8+
* Checks if the input string can be rearranged into a palindrome
9+
* @param {string} str input string to check against
10+
* @return {boolean} whether the input string can be rearranged into a palindrome
11+
*
12+
* We don't actually have to rearrange the string to solve this problem; we only need to check its contents.
13+
* If the string is of odd length, then each character in the string has to appear an even number of times, except one.
14+
* If the string is of even length, then each character in the string has to appear an even number of times.
15+
* We can create a letter frequency map which takes O(N) time to loop through the string, and O(N) space to build.
16+
* Looping through the object key-value pairs again is an O(N) operation in the worst case where we loop through it all.
17+
*
18+
* Runtime: O(N)
19+
* Space: O(N)
20+
*
21+
*/
22+
const palindromePerm = (str) => {
23+
const letterFreqs = {};
24+
let length = 0;
25+
for (const letter of str) {
26+
if (letter === " ") continue;
27+
28+
letterFreqs[letter.toLowerCase()] =
29+
(letterFreqs[letter.toLowerCase()] || 0) + 1;
30+
length += 1;
31+
}
32+
33+
let slack = length % 2 == 1;
34+
for (const letterFreq of Object.values(letterFreqs)) {
35+
if (letterFreq % 2 === 0) continue;
36+
37+
if (!slack) return false;
38+
39+
slack = !slack;
40+
}
41+
42+
return true;
43+
};
44+
45+
describe(module.filename, () => {
46+
it("should return true when the input string can be rearranged in the form of a palindrome.", () => {
47+
assert.ok(palindromePerm("Tact C o a "));
48+
assert.ok(palindromePerm("RaCeCaR"));
49+
});
50+
it("should return false when the input string cannot be rearranged in the form of a palindrome.", () => {
51+
assert.ok(!palindromePerm("techqueria"));
52+
});
53+
});

0 commit comments

Comments
 (0)