Skip to main content
InterviewHubPRO
Section Overview
Q526

Question 526 of 536

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)

98%
JavaScript & V8 Internals (536 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)

How do you implement Run-Length Encoding (RLE) string compression and decompression?

mid LevelCode ExampleFormsPerformanceHTTP & REST APIs

Run-Length Encoding (RLE) is a lossless data compression algorithm where consecutive repeated characters are replaced by the character and its frequency count (e.g., "aabcccccaaa" → "a2b1c5a3").

1. Compression (compressString)

javascript
function compressString(str) {
  if (!str) return "";

  let compressed = "";
  let count = 1;

  for (let i = 0; i < str.length; i++) {
    if (str[i] === str[i + 1]) {
      count++;
    } else {
      compressed += str[i] + count;
      count = 1;
    }
  }

  // Interview rule: if compressed string is not shorter than original, return original
  return compressed.length < str.length ? compressed : str;
}

console.log(compressString("aabcccccaaa")); // "a2b1c5a3"
console.log(compressString("abcdef"));       // "abcdef" (compression adds overhead, returns original)

2. Decompression (decompressString)

javascript
function decompressString(compressedStr) {
  if (!compressedStr) return "";

  let result = "";
  let i = 0;

  while (i < compressedStr.length) {
    const char = compressedStr[i];
    i++;

    // Extract multi-digit counts (e.g., "a12")
    let countStr = "";
    while (i < compressedStr.length && /\d/.test(compressedStr[i])) {
      countStr += compressedStr[i];
      i++;
    }

    const count = parseInt(countStr, 10);
    result += char.repeat(count);
  }

  return result;
}

console.log(decompressString("a2b1c5a3")); // "aabcccccaaa"

Complexity:

  • Time Complexity: $\mathcal{O}(N)$ where $N$ is string length.
  • Space Complexity: $\mathcal{O}(N)$ to store the compressed/decompressed output.