101 Logo
onenoughtone

Code Implementation

File Compression System Implementation

Below is the implementation of the file compression system:

solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
function compress(s) {
// Handle edge case
if (s.length <= 1) return s;
// Two-pointer approach
let result = "";
let count = 1;
for (let i = 1; i <= s.length; i++) {
// If current character is the same as previous, increment count
if (i < s.length && s[i] === s[i-1]) {
count++;
} else {
// Add the previous character to result
result += s[i-1];
// Add the count if it's greater than 1
if (count > 1) {
result += count;
}
// Reset count for the next character
count = 1;
}
}
// Return the shorter string
return result.length < s.length ? result : s;
}
// Alternative approach: Two-pass solution
function compressOptimized(s) {
// Handle edge case
if (s.length <= 1) return s;
// First pass: Calculate compressed length
let compressedLength = 0;
let count = 1;
for (let i = 1; i <= s.length; i++) {
if (i < s.length && s[i] === s[i-1]) {
count++;
} else {
compressedLength += 1; // for the character
if (count > 1) {
compressedLength += count.toString().length; // for the count
}
count = 1;
}
}
// If compression doesn't save space, return original
if (compressedLength >= s.length) {
return s;
}
// Second pass: Create compressed string
let result = "";
count = 1;
for (let i = 1; i <= s.length; i++) {
if (i < s.length && s[i] === s[i-1]) {
count++;
} else {
result += s[i-1];
if (count > 1) {
result += count;
}
count = 1;
}
}
return result;
}
// Test cases
console.log(compress("aabcccccaaa")); // "a2bc5a3"
console.log(compress("abcdef")); // "abcdef"
console.log(compress("aaaaabbbbaaaabbddc")); // "a5b4a4b2d2c"

Step-by-Step Explanation

Let's break down the implementation:

  1. Handle Edge Cases: Check for empty strings or strings with a single character and return them as is.
  2. Initialize Variables: Set up a result string (or StringBuilder) and a counter for consecutive characters.
  3. Iterate Through String: Loop through the string, comparing each character with the previous one.
  4. Count Consecutive Characters: If the current character matches the previous one, increment the counter.
  5. Append to Result: When a different character is encountered, append the previous character and its count (if > 1) to the result.
  6. Handle Last Character: After the loop, make sure to process the last character and its count.
  7. Compare Lengths: Return the compressed string only if it's shorter than the original string.
ProblemSolutionCode
101 Logo
onenoughtone