Simple data compression algorithm

Simple data compression algorithm is one of the programming question recently asked me in the interview, So I wanted to share it. happy coding and all the best.

PYTHON PROGRAM

Luminari

7/14/20241 min read

Question:

write a program for simple data compression algorithm

Example:

data = [1,2,3,4,0,0,0,3,4,6,0,0,0,21,2,3]

out = [1,2,3,4,"3x0",4,6,"2x0",21,2,3]

Logic:

  1. Initialize comp_count to 1 and an empty list called result.

  2. Iterate over the input list data (except for the last element).

  3. If the current element is the same as the next element, increment comp_count.

  4. If the current element is different from the next element:

    • If there were consecutive identical elements (i.e., comp_count > 1), append the count and the element to result.

    • Append the current element to result.

    • Reset comp_count to 1 for the next element.

  5. Return the compressed list in the format “count x element”.

Solution in python:

# Example 1

data = [1,2,3,4,0,0,0,3,4,6,0,0,0,21,2,3]

out = [1,2,3,4,"3x0",4,6,"2x0",21,2,3]

# Example 2

data = [1, 1, 2, 2, 2, 3, 4, 4, 4, 4],

output would be ['2x1', '3x2', 3, '4x4']

Preparing for interview?