Skip to content

Commit 8bcd43a

Browse files
authored
avc278 - 1.06 - Javascript (#61)
Added my solution to the Chapter 1 Problem 6 folder.
1 parent 1df57f2 commit 8bcd43a

File tree

1 file changed

+57
-0
lines changed
  • JavaScript/chapter01/p06_string_compression

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// String Compression: Implement a method to perform basic string compression using the counts of repeated characters.
2+
// For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than
3+
// the original string, your method should return the origin string. You can assume the string has only uppercase and
4+
// lowercase letters (a-z).
5+
6+
const assert = require("assert");
7+
8+
/**
9+
* Returns the compressed version of the string if applicable
10+
* @param {string} str input string to compress
11+
* @return {string} either the compressed string, or the string
12+
*
13+
* Storing the outputStrArr is at worst size 2N for an input string whose size is N (still O(N) additional space).
14+
* Storing and updating the pointers `idx`, `next`, and `freq` take O(1) additional space and O(1) time.
15+
* As we iterate through the str in the outer while loop, in one extreme, assuming no repeating letters in a sequence,
16+
* idx increments by 1 each iteration, and so it's O(N) runtime. On the other extreme, assuming all repeating letters,
17+
* this would be O(N) on the outer loop, and O(N) in the inner while loop. The trick to knowing this is still O(N)
18+
* and not O(N^2) is the fact that we don't visit any one index pointer more than once in our two while loops.
19+
* Both loops are still just part of the same loop, which results in O(N).
20+
*
21+
* Runtime: O(N)
22+
* Space: O(N)
23+
*
24+
*/
25+
const compress = (str) => {
26+
let outputStrArr = [];
27+
let idx = 0;
28+
29+
while (idx < str.length) {
30+
const currLetter = str[idx];
31+
let freq = 1;
32+
33+
let next = idx + 1;
34+
while (next < str.length && currLetter === str[next]) {
35+
next += 1;
36+
freq += 1;
37+
}
38+
39+
outputStrArr.push(currLetter);
40+
outputStrArr.push(freq);
41+
idx = next;
42+
}
43+
44+
return outputStrArr.length < str.length ? outputStrArr.join("") : str;
45+
};
46+
47+
describe(module.filename, () => {
48+
it("should compress a string with repeated characters.", () => {
49+
assert.ok(compress("aabcccccaaa", "a2b1c5a3"));
50+
assert.ok(compress("aaaaaaaaaaa", "a11"));
51+
});
52+
it("should not compress a string whose str length is less than the compressed version.", () => {
53+
assert.equal(compress("tech"), "tech");
54+
assert.equal(compress("abcdefg"), "abcdefg");
55+
assert.equal(compress(""), "");
56+
});
57+
});

0 commit comments

Comments
 (0)