AP Computer Science Principles • Data

Data Compression

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

Computer science principles illustration with a network, database, and code file
Inside this lesson 10 sections 5 questions 6 figures

SECTION 1

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.

SECTION 2

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.

SECTION 3

Visualizing Lossless vs. Lossy Compression

LOSSLESS vs. LOSSY COMPRESSION PIPELINELOSSLESS PATHOriginal File800 KBCompressionFind patterns,encode efficientlyCompressed350 KBDecompressed800 KB ✓100% identical to originalLOSSY PATHOriginal File800 KBCompressionDiscard imperceptibledata + encodeCompressed80 KBDecompressedValues differApproximation — data lost
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.

A teal-and-amber feather with fine barbs on a dark background.Fine feather edges and smooth color gradients reveal what survives compression. Lossless decoding restores the input values exactly; lossy decoding can change them.

An original feather crop is compared with lossless and lossy reconstructions at the same 64-by-64 pixel dimensions.The same 64-by-64 RGB crop passes through both processes. Lossless decoding restores every channel value; the lossy quantizer changes values while preserving the decoded dimensions. Compressed byte count and decoded pixel count measure different things.

SECTION 4

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

CompressionRatio=OriginalSize÷CompressedSizeCompression 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.

SECTION 5

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.

HUFFMAN TREE — Encoding "ABRACADABRA"Frequencies: A=5, B=2, R=2, C=1, D=1 | Total=11 characters0111A:5Code: 0601401B:2Code: 100R:2Code: 101201C:1Code: 110D:1Code: 111Encoded: A B R A C A D A B R A0 100 101 0 110 0 111 0 100 101 0 → 23 bits (vs. 33 at 3 bits/char)
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.
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

Comparison of fixed-length and Huffman variable-length encoding for ABRACADABRA

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.

SECTION 6

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 (27 characters). We will compress this row using run-length encoding and compute the compression ratio.

RLE Compression of a Pixel Row

  1. 1

    Step 1 — Identify Runs

    Scan 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. 2

    Step 2 — Encode Each Run

    Replace 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. 3

    Step 3 — Calculate Compression Ratio

    Compression Ratio = Original Size ÷ Compressed Size = 27 ÷ 11 ≈ 2.45. The compressed version is approximately 41% the size of the original.
    Compression Ratio ≈ 2.45 : 1
  4. 4

    Step 4 — Verify Losslessness

    To 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.

A black-and-white row shows runs of 7, 4, 4, 10 and 2 pixels. Below are codes A=0, B=100, R=101, C=110, D=111 and the total 23 payload bits.The five black/white runs contain 7 + 4 + 4 + 10 + 2 = 27 pixels, encoded as 7B4W4B10W2B. Separately, ABRACADABRA uses five 1-bit A codes and six 3-bit codes: 23 payload bits, plus the codebook or header.Open full diagram

SECTION 7

Lossless vs. Lossy — Strengths & Limitations

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

Side-by-side comparison of lossless and lossy compression characteristics

✦

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.

Original and lossless rows read 12, 25, 39, 61, 86, 120, 171, 224. The lossy row reads 0, 32, 32, 64, 96, 128, 160, 224.For these eight grayscale values, lossless decoding restores every value. Rounding to the nearest multiple of 32 changes seven values while preserving eight positions; 224 already lies on the quantization grid.Open full diagram

SECTION 8

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.

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

How AP CSP compression concepts connect to more advanced computer science topics

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.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

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?
  • A. The decompressed file will be smaller than the original file.
  • B. The decompressed file will be identical to the original file.
  • C. The decompressed file will contain most but not all of the original data.
  • D. The decompressed file will be larger than the original because the compression metadata is added.
Show answer (B)
B is correct. The defining property of lossless compression is that the original data can be perfectly reconstructed from the compressed version. A is wrong because decompression restores the original size, not a smaller size. C describes lossy compression, not lossless. D is incorrect because while compressed files may include metadata, the decompressed output reconstructs the original data exactly, with no extra metadata appended.

Question 2: BASIC CALCULATION

A 5-megabyte (MB) audio file is compressed to 0.5 MB using a lossy algorithm. What is the compression ratio?
  • A. 1 : 10
  • B. 5 : 1
  • C. 10 : 1
  • D. 0.1 : 1
Show answer (C)
C is correct. Compression ratio = Original Size ÷ Compressed Size = 5 MB ÷ 0.5 MB = 10. This is expressed as 10 : 1, meaning the original is 10 times larger than the compressed version. A (1 : 10) is the ratio inverted — it would mean the compressed file is larger. B (5 : 1) uses the wrong divisor. D (0.1 : 1) confuses the fraction 0.5/5 with the ratio.

Question 3: INTERMEDIATE

A photographer saves the same image in both PNG and JPEG formats. Which TWO of the following statements are true? (Select two.)
  • A. The PNG file can be converted back to the exact original pixel data.
  • B. The JPEG file will always be larger than the PNG file.
  • C. Repeatedly opening and re-saving the JPEG at the same quality setting can cause the image to degrade further.
  • D. The PNG format uses lossy compression to achieve smaller file sizes than JPEG for photographs.
Show answer (AC)
A and C are correct. PNG uses lossless compression, so the pixel data is perfectly preserved (A is true). JPEG is lossy, and each time a JPEG is decoded and re-encoded, a new round of lossy compression occurs, causing generation loss — the accumulation of artifacts over multiple save cycles (C is true). B is incorrect because JPEG typically produces smaller files than PNG for photographic images, which is the reason photographers choose JPEG when file size matters. D is incorrect because PNG is a lossless format, not lossy.

Question 4: APPLIED

3 pts
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.
Show answer
Rubric (3 points): Point 1 (Calculation): Compression Ratio = 1,411 ÷ 64 ≈ 22 : 1. The student must show or clearly state the division and arrive at approximately 22 : 1. Point 2 (Bandwidth explanation): A user on a slow connection benefits from the Low setting because the smaller data rate (64 kbps) requires less bandwidth, reducing buffering and enabling uninterrupted playback. The trade-off is reduced audio quality, but continuous playback is preferable to constant interruptions. Point 3 (Specific lossy technique): Acceptable answers include: frequencies above 16 kHz that most adults cannot hear, quiet sounds that are masked by louder nearby frequencies (psychoacoustic masking), or fine stereo separation details. The student must name a specific type of discarded information, not just state 'some data is removed.'

Question 5: CRITICAL THINKING

4 pts
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.
Show answer
Rubric (4 points): Point 1 (Text recommendation): A lossless format such as ZIP or GZIP is required for legal contracts. Legal documents must be preserved exactly — any alteration, even a single changed character, could change the meaning of a clause. Lossy compression would permanently discard data, which is unacceptable for legal records where bit-for-bit fidelity is essential. Point 2 (Photo recommendation): For photographs of signed pages, a lossless format like PNG or TIFF is strongly recommended in this legal context, even though lossy JPEG would produce smaller files. Since these photos serve as legal evidence of signatures, any lossy artifacts that alter fine details of handwriting could undermine authenticity. A student could also acceptably argue for high-quality JPEG if they justify that the photographs are secondary to the text and the quality setting is sufficiently high — but they must acknowledge the trade-off. Point 3 (ZIP-on-JPEG evaluation): Compressing a JPEG file with ZIP will yield negligible additional savings. JPEG files have already had their redundancy removed by the JPEG compression algorithm — the remaining data appears nearly random to a lossless compressor like ZIP. ZIP works by finding patterns and redundancy, but a well-compressed JPEG has very little exploitable redundancy left. The student must connect this to the concept that compression removes redundancy, and data that has already been compressed contains minimal remaining redundancy. Point 4 (Data integrity): Lossless compression supports data integrity verification because the decompressed output must be bit-for-bit identical to the original. A hash (checksum) of the original can be compared to a hash of the decompressed file — any mismatch indicates corruption. With lossy compression, the original data is permanently altered, so a hash of the decompressed file will never match the original uncompressed file. This makes it harder to distinguish between expected lossy alterations and unintended corruption. The student must explain the connection between lossless reversibility and integrity verification.

SUMMARY

Data Compression — Summary

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