AP COMPUTER SCIENCE PRINCIPLES • DATA

Data Compression

Reducing data size to store and transmit information more efficiently while balancing fidelity and file size.

Historical Context & Motivation

From the earliest days of telegraphy, engineers have searched for ways to encode messages using fewer symbols. Data compression — the process of reducing the number of bits needed to represent information — is not merely a modern convenience but a foundational problem in information science. As digital media expanded from kilobytes of text to gigabytes of video, the ability to shrink data without losing essential meaning became critical for storage, bandwidth, and cost. Understanding data compression requires appreciating both the mathematical theory behind it and the practical trade-offs that arise when encoding real-world data.

1838
Morse Code
Samuel Morse designs a variable-length encoding where common letters like 'E' use shorter codes. This is arguably the first practical compression scheme.
1948
Shannon's Information Theory
Claude Shannon publishes "A Mathematical Theory of Communication," establishing entropy as the theoretical limit on lossless compression and launching the entire field of information theory.
1952
Huffman Coding
David Huffman, a graduate student at MIT, develops an optimal prefix-free coding algorithm that assigns shorter bit patterns to more frequent symbols — a technique still used today inside formats like ZIP.
1977–1978
Lempel-Ziv Algorithms
Abraham Lempel and Jacob Ziv publish LZ77 and LZ78, dictionary-based algorithms that power GIF, PNG, and many general-purpose compression tools.
1992–2001
JPEG & MP3 Standards
Lossy compression enters mainstream use. JPEG (1992) and MP3 (1993) exploit human perceptual limitations to achieve dramatic file-size reductions for images and audio, enabling the multimedia web era.

The central question that runs through this history is deceptively simple: How few bits do we truly need to represent a piece of information, and what happens when we discard some of the data to use even fewer? That question divides compression into two families — lossless and lossy — each with distinct guarantees and trade-offs that the AP CSP exam expects you to understand and evaluate.

Core Principles & Definitions

All compression techniques rest on a single insight: most data contains redundancy — patterns, repetitions, or information that is less important to human perception. Compression algorithms identify and exploit that redundancy, replacing it with shorter representations. Before examining specific techniques, it is essential to internalize several foundational concepts that appear repeatedly on the AP CSP exam.

1

Lossless Compression

Reduces file size such that the original data can be perfectly reconstructed from the compressed version. No information is lost. Examples include ZIP, PNG, and FLAC.
2

Lossy Compression

Achieves greater size reduction by permanently discarding some data — often information that is difficult for humans to perceive. The original cannot be exactly recovered. Examples include JPEG, MP3, and MPEG.
3

Compression Ratio

The ratio of original size to compressed size. A compression ratio of 4 : 1 means the compressed file is one-quarter the size of the original. Higher ratios indicate more aggressive compression.
4

Redundancy

Repeated or predictable patterns in data. Spatial redundancy (adjacent pixels of the same color), temporal redundancy (consecutive video frames), and statistical redundancy (letter frequencies in English) are all exploitable.
5

Entropy (Information Content)

Shannon's entropy measures the average minimum bits per symbol needed to encode a message. It sets the theoretical floor for lossless compression — you cannot compress below entropy without losing data.
KEY TAKEAWAY
Think of compression like packing a suitcase. Lossless compression is like rolling your clothes tightly — everything is still there when you unpack, just arranged more efficiently. Lossy compression is like leaving some items at home — you have a lighter suitcase, but you can never get those items back. The key exam distinction is reversibility: lossless is reversible, lossy is not.

Visualizing Lossless vs. Lossy Compression

The diagram contrasts the two compression pipelines. In the lossless path (top), the decompressed output is bit-for-bit identical to the original 800 KB file. In the lossy path (bottom), the compressed file drops to 80 KB — a 10 : 1 ratio — but the decompressed version is only an approximation. Data that was discarded can never be recovered.

Notice the fundamental trade-off: the lossy path achieves a much smaller compressed file (80 KB vs. 350 KB), but the cost is irreversibility. Once data is removed during lossy compression, no decompression algorithm can regenerate it. The lossless path guarantees a perfect round-trip — compress and decompress, and you are back where you started. This is why lossless formats are mandatory for text, code, medical images, and legal documents, while lossy formats are acceptable (and often preferred) for consumer media like photos, music, and streaming video, where tiny perceptual differences go unnoticed.

How Compression Algorithms Work

Run-Length Encoding (RLE)

One of the simplest lossless techniques is run-length encoding (RLE). Instead of storing every individual value, RLE replaces consecutive runs of the same value with a single value and a count. For example, the pixel row WWWWWBBBWW (10 characters) becomes 5W3B2W (6 characters). RLE works exceptionally well on data with long homogeneous runs, such as simple bitmap images or fax transmissions, but offers little benefit on data with high variability like photographs.

COMPRESSION RATIO
Compression Ratio = Original Size ÷ Compressed Size
A ratio greater than 1 indicates the file shrank. For the RLE example above: 10 ÷ 6 ≈ 1.67, meaning the compressed version is about 60% the size of the original.

Huffman Coding

A more sophisticated lossless strategy is Huffman coding, which exploits statistical redundancy by assigning shorter bit patterns to symbols that occur more frequently and longer patterns to rare symbols. Consider English text: the letter 'E' appears far more often than 'Z,' so giving 'E' a 2-bit code and 'Z' a longer code reduces the total number of bits. Huffman coding constructs a binary tree from symbol frequencies and generates an optimal prefix-free code — no code is the start of another code, so the encoded bitstream can be decoded unambiguously.

Dictionary-Based Compression (LZW)

The Lempel-Ziv-Welch (LZW) algorithm builds a dictionary of recurring substrings as it scans the data. When a substring appears again, the algorithm outputs a short dictionary index instead of the full substring. The GIF image format and the Unix compress utility both use LZW. Its strength lies in adapting to whatever patterns the data contains without prior knowledge of the source.

Lossy Techniques — Perceptual Coding

Lossy algorithms leverage models of human perception. JPEG exploits the fact that the human eye is more sensitive to brightness changes than to color changes, so it stores color information at lower resolution. MP3 uses psychoacoustic models to discard audio frequencies that are masked by louder neighboring frequencies. In both cases, the algorithm throws away data that most people will never notice is missing, achieving compression ratios that are impossible with lossless methods alone.

Compression Techniques in Detail

To build a deeper understanding of how compression operates in practice, it helps to walk through a concrete example of Huffman coding and then visualize how the encoding tree determines the bit assignments for each symbol.

This Huffman tree encodes the string "ABRACADABRA." The most frequent character 'A' (frequency 5) receives the shortest code (0 — just 1 bit), while the least frequent characters 'C' and 'D' receive 3-bit codes. The total encoding uses 23 bits instead of the 33 bits a fixed 3-bit-per-character scheme would require.
Comparison of fixed-length and Huffman variable-length encoding for ABRACADABRA
SymbolFrequencyFixed Code (3 bits)Huffman CodeBits Saved per Occurrence
A500002 bits × 5 = 10
B20011000 bits × 2 = 0
R20101010 bits × 2 = 0
C10111100 bits × 1 = 0
D11001110 bits × 1 = 0

The savings come almost entirely from the most frequent symbol. By giving 'A' a 1-bit code instead of a 3-bit code, we save 2 bits across each of its 5 occurrences, for a total savings of 10 bits. The less frequent symbols (B, R, C, D) retain 3-bit codes, which is the same length as the fixed scheme, so they contribute no additional savings. This illustrates a general principle of Huffman coding: the benefit is proportional to the skewness of the frequency distribution. If all symbols occurred equally often, Huffman coding would offer no improvement over a fixed-length code.

Worked Example: Run-Length Encoding

Consider a simple black-and-white image stored as a grid of pixel values, where 'B' represents a black pixel and 'W' represents a white pixel. Suppose one row of the image is: BBBBBBBWWWWBBBBWWWWWWWWWWBB (26 characters). We will compress this row using run-length encoding and compute the compression ratio.

RLE Compression of a Pixel Row
1
Step 1 — Identify RunsScan the row left to right and group consecutive identical characters. The runs are: 7 B's, 4 W's, 4 B's, 10 W's, 2 B's.
2
Step 2 — Encode Each RunReplace each run with a count followed by the character. The encoded result is: 7B4W4B10W2B. This representation uses 11 characters (treating '10' as two characters in the symbol stream).
Encoded: 7B4W4B10W2B (11 characters)
3
Step 3 — Calculate Compression RatioCompression Ratio = Original Size ÷ Compressed Size = 26 ÷ 11 ≈ 2.36. The compressed version is approximately 42% the size of the original.
Compression Ratio ≈ 2.36 : 1
4
Step 4 — Verify LosslessnessTo decompress, expand each count-character pair: 7B → BBBBBBB, 4W → WWWW, 4B → BBBB, 10W → WWWWWWWWWW, 2B → BB. Concatenating these yields the original string exactly: BBBBBBBWWWWBBBBWWWWWWWWWWBB. The process is perfectly reversible.
Lossless ✓ — original data fully reconstructed
⚠️ When RLE Fails
If the pixel row were BWBWBWBWBWBW (12 characters), the RLE encoding would be 1B1W1B1W1B1W1B1W1B1W1B1W (24 characters) — actually larger than the original! This illustrates that no compression algorithm is guaranteed to reduce every possible input. Highly random or alternating data can resist or even be expanded by certain techniques.

Lossless vs. Lossy — Strengths & Limitations

Side-by-side comparison of lossless and lossy compression characteristics
CriterionLosslessLossy
Data FidelityExact reconstruction guaranteedApproximation only; original unrecoverable
Typical Ratio2 : 1 to 4 : 15 : 1 to 50 : 1 or higher
Common FormatsZIP, PNG, FLAC, GIFJPEG, MP3, MPEG-4, AAC
Best ForText, code, medical images, legal documentsPhotos, music, video, streaming
Quality SettingN/A — always perfectUser-adjustable quality slider (e.g., JPEG 1–100)
Repeated CompressionNo degradation — output is bit-identical each timeEach round discards more data, causing generation loss
KEY TAKEAWAY
The choice between lossless and lossy compression is an engineering trade-off, not a quality judgment. A hospital must use lossless compression for CT scans because a single altered pixel could affect a diagnosis. A streaming service uses lossy compression for video because sending uncompressed 4K footage would require bandwidth that most home connections cannot provide. Context determines which approach is appropriate, and many modern systems combine both — for example, a PNG screenshot inside a ZIP archive uses lossless compression at two levels, while a JPEG photo is lossy internally but can be losslessly archived in a ZIP.

Connections to Information Theory & Beyond

Data compression is not an isolated topic — it sits at the intersection of several deep ideas in computer science, including information theory, algorithmic complexity, and network efficiency. Shannon's source coding theorem proves that no lossless compression algorithm can, on average, encode messages using fewer bits per symbol than the entropy of the source. This theoretical floor applies universally — it constrains ZIP just as it constrains any future algorithm yet to be invented.

How AP CSP compression concepts connect to more advanced computer science topics
ConceptAP CSP LevelAdvanced Extension
Compression RatioOriginal ÷ Compressed, higher is betterRate-distortion theory quantifies the optimal trade-off between compression ratio and quality loss in lossy systems
Huffman CodingVariable-length codes based on frequencyArithmetic coding achieves even closer-to-entropy performance by encoding entire messages as single fractions
Lossy ImageJPEG removes perceptually unimportant dataJPEG 2000 and HEIF use wavelet transforms and more advanced perceptual models for better quality at the same file size
Network ImpactSmaller files transfer faster over limited bandwidthAdaptive bitrate streaming (e.g., HLS, DASH) dynamically adjusts lossy compression quality based on real-time network conditions

Compression also has profound implications for the Internet of Things, cloud storage pricing, and sustainability — every byte we avoid transmitting reduces energy consumption in data centers and network infrastructure. As data generation continues to accelerate, the principles you learn in this lesson become even more relevant. Future courses in algorithms, machine learning (which increasingly uses learned compression models), and systems design will all build on these foundations.

Practice Problems

1
A user compresses a text file using a lossless compression algorithm and then decompresses it. Which of the following is true about the decompressed file?
2
A 5-megabyte (MB) audio file is compressed to 0.5 MB using a lossy algorithm. What is the compression ratio?
3
A photographer saves the same image in both PNG and JPEG formats. Which TWO of the following statements are true? (Select two.)
PROBLEM 4APPLIED
A music streaming service allows users to choose between three quality levels: Low (64 kbps), Medium (160 kbps), and High (320 kbps). All three levels use lossy compression (MP3 format). The original uncompressed audio is encoded at 1,411 kbps (CD quality). (a) Calculate the compression ratio for the Low quality setting. (b) Explain why a user on a slow mobile connection might prefer Low quality despite the loss of audio fidelity. (c) Describe one specific type of audio information that is likely discarded by the lossy compression algorithm.
PROBLEM 5CRITICAL THINKING
A software company is designing a system to archive millions of legal contracts (text documents) and associated photographs of signed pages. (a) Recommend and justify a specific compression format for the text documents. Explain why this format is more appropriate than the alternative type of compression. (b) Recommend and justify a specific compression format for the photograph images. Explain why this format is more appropriate than the alternative type. (c) A junior developer suggests compressing the JPEG photographs a second time using ZIP to save additional space. Evaluate this suggestion — will it significantly reduce file size? Justify your answer using principles of redundancy. (d) The company is concerned about long-term data integrity. Explain how the choice between lossless and lossy compression affects the ability to verify that archived documents remain unchanged over time.

Data Compression — Summary

Data compression reduces the number of bits needed to represent information by exploiting redundancy in the data. Lossless compression (ZIP, PNG, FLAC) guarantees that the original data can be perfectly reconstructed, making it essential for text, code, and sensitive records. Lossy compression (JPEG, MP3, MPEG) permanently discards perceptually less important data to achieve much smaller file sizes, which is acceptable for consumer media but irreversible. Key algorithms include run-length encoding (replacing runs with counts), Huffman coding (shorter codes for frequent symbols), and dictionary-based methods like LZW.

The compression ratio (original size ÷ compressed size) quantifies effectiveness, and no algorithm can compress every input — highly random data resists compression. Shannon's entropy sets the theoretical floor for lossless compression. On the AP CSP exam, expect questions about when to use lossless vs. lossy, how compression affects data quality, and how to calculate compression ratios. Remember: lossless is reversible, lossy is not, and the right choice depends on context.

Varsity Tutors • AP Computer Science Principles • Data Compression