EvalFrame Technical Mock Interviews & Coding Practice

String Compression

Easy · Two Pointers / String · Algorithm problem · all problems

Implement a method to perform basic string compression using the counts of repeated characters. For example, the string "aabcccccaaa" would become "a2b1c5a3". If the "compressed" string would not become smaller than the original string, your method should return the original string. You can assume the string has only uppercase and lowercase letters (a-z). **Examples:** ```typescript compressString("aabcccccaaa") // "a2b1c5a3" compressString("abcd") // "abcd" (compressed is "a1b1c1d1", not shorter) compressString("aabb") // "aabb" (compressed is "a2b2", equal length, not shorter) ```

Solve It in the BrowserPractice Explaining It Out Loud

Optimal Approach

  • Time complexity: O(n)
  • Space complexity: O(n)

We iterate through the input string of length n once. String concatenation or array joining for compressed output visits each character once, leading to O(n) linear execution time.

Follow-Up Questions Interviewers Ask About String Compression

  • In languages like Java or older JavaScript engines, why is string concatenation in a loop problematic?
    Strings are immutable. Repeatedly doing `compressed += char` creates a brand new string copy on every iteration, turning an O(n) loop into an O(n^2) operation. Using an array of parts and joining them at the end (`[].join("")`) is preferred for large strings.
  • How would you compress an array of characters in-place with O(1) extra memory (LeetCode 443)?
    Use two pointers (a read pointer and a write pointer). Iterate through consecutive runs of characters and overwrite the original array directly at the write pointer with the character followed by its count digits.
  • Can you check if the compressed string will be shorter BEFORE actually building the string?
    Yes! You can do a preliminary counting pass that simply calculates the total length the compressed string would have without allocating memory. If the projected length >= s.length, return s immediately.

Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.