{
  "id": "run-length-encoding",
  "title": "Run-length encoding",
  "lang": "en",
  "source_lang": "en",
  "summary": "Run-length encoding is a lossless compression technique that replaces consecutive repetitions of a value with a representation of that value and its repetition count.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "RLE",
    "Run-length coding"
  ],
  "generated_at": "2026-11-04",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/run-length-encoding/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/run-length-encoding/",
      "json": "https://aiwiki.page/zh/run-length-encoding.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "Run-length encoding (RLE) is a form of lossless data compression that represents consecutive occurrences of the same value as a single run, usually described by the value and a repetition count. It is effective for data containing long stretches of identical symbols, such as simple raster images, binary masks, and repeated values in database columns. RLE is a family of encoding schemes rather than a single standardized file format: different schemes use different count representations, literal blocks, and rules for identifying runs."
    },
    {
      "heading": "Basic principle",
      "text": "A run is a maximal consecutive sequence of equal symbols. For example, the sequence\n\nAAAAABBBCCAAAA\n\ncontains four runs and can be represented as:\n\n(A, 5), (B, 3), (C, 2), (A, 4)\n\nDecoding expands each pair into the indicated number of copies of its value, recovering the original sequence exactly.\n\nMore formally, a sequence of length \\(n\\) can be divided into \\(r\\) runs:\n\n\\[x = v_1^{\\ell_1}v_2^{\\ell_2}\\cdots v_r^{\\ell_r},\\]\n\nwhere \\(v_i\\) is the value of run \\(i\\), \\(\\ell_i\\) is its positive length, and adjacent run values differ. The lengths satisfy\n\n\\[\\sum_{i=1}^{r}\\ell_i=n.\\]\n\nThe symbols being encoded need not be characters. They may be individual bits, bytes, pixels, integers, or larger records. What counts as repetition depends on the unit selected: repeated pixels do not necessarily form repeated bytes when each pixel occupies several bytes.\n\nThe notation (A, 5) is explanatory, not a universal storage format. An actual encoding must specify field sizes, count limits, and how a decoder distinguishes counts, values, and control information."
    },
    {
      "heading": "Encoding and decoding",
      "text": "A basic encoding algorithm scans the input from left to right, retaining the current value and its count. When a different value appears, it emits the completed run and starts another. After reaching the end, it emits the final run.\n\nUsing abstract pairs, the process can be expressed in pseudocode:\n\nif input is empty:\n    return\n\nvalue = first input symbol\ncount = 1\n\nfor each remaining symbol:\n    if symbol == value:\n        count = count + 1\n    else:\n        emit(value, count)\n        value = symbol\n        count = 1\n\nemit(value, count)\n\nA real implementation must also handle the largest representable count. A run that exceeds that limit can be split into several encoded records.\n\nEncoding has \\(O(n)\\) time complexity. Decoding into a fully expanded sequence also takes \\(O(n)\\) time, because every output symbol must be written. Both operations can use constant auxiliary working memory when input and output are streamed and the count field has a fixed maximum size. Storing the entire encoded or decoded result requires additional space."
    },
    {
      "heading": "Compression effectiveness",
      "text": "RLE benefits from long consecutive repetitions, not merely from the frequent occurrence of particular values. The sequences AAAAABBBBB and ABABABABAB have the same symbol frequencies, but contain two and ten runs respectively.\n\nSuppose each original symbol occupies \\(s\\) bits and each encoded run uses \\(s\\) bits for its value plus \\(c\\) bits for its count. Ignoring headers, padding, and count overflow, the original and encoded sizes are\n\n\\[L_{\\text{original}}=ns, \\qquad L_{\\text{encoded}}=r(s+c).\\]\n\nCompression occurs when\n\n\\[\\frac{n}{r}>1+\\frac{c}{s}.\\]\n\nThus, under this simplified format, the average run length must exceed the overhead associated with storing a count. With an eight-bit value and an eight-bit count, runs average more than two symbols before the representation becomes smaller.\n\nRLE can expand data substantially when runs are short. In a format that always stores one value byte and one count byte per run, input with no identical adjacent bytes roughly doubles in size. Practical formats often reduce this penalty by providing literal blocks."
    },
    {
      "heading": "Main variants",
      "text": "Value–count pairs\n\nThe simplest form stores a value and a count for every run. Counts may have fixed width or use a variable-length integer representation. Fixed-width counts simplify parsing but limit run length; variable-length counts accommodate larger runs while making the encoding rules more elaborate.\n\nCounts may represent either the actual run length or an offset from a minimum length. For example, a stored count of zero might mean one occurrence. Such conventions must be defined by the format.\n\nLiteral and repeated blocks\n\nMany byte-oriented schemes distinguish between:\n\n- Literal blocks, whose bytes are copied unchanged.\n- Repeated blocks, which specify a value and its repetition count.\n\nControl bytes identify the block type and length. This avoids attaching a count to every nonrepeating byte, although literal-block headers still introduce overhead.\n\nPackBits, used as a compression option in TIFF images, is a familiar example. Its packet structure supports literal byte sequences and repeated-byte runs. Other image formats use different control conventions, so their RLE streams are not interchangeable.\n\nBinary run lengths\n\nFor binary data, successive runs alternate between zero and one. If the initial value is known or stored separately, the encoded representation can contain only run lengths.\n\nFor example:\n\n000011100\n\ncan be represented by initial value 0 and lengths 4, 3, 2. Image-oriented schemes may assume that a row begins with a particular color and use a zero-length initial run when necessary.\n\nRuns of a designated value\n\nSome schemes encode only runs of a selected value, commonly zero, while representing other values differently. This is useful when a transformation produces many zero values but few long runs of arbitrary nonzero values."
    },
    {
      "heading": "Applications and related techniques",
      "text": "Images and document transmission\n\nRLE suits images with large uniform regions, including icons, diagrams, monochrome documents, and some screen graphics. Certain BMP variants provide RLE modes for indexed-color images, while TIFF supports PackBits.\n\nImage layout affects effectiveness. Encoding rows independently prevents runs from crossing row boundaries. A different scanning order can produce different run lengths even when the image itself is unchanged.\n\nFacsimile coding methods exploit alternating black and white runs in scanned documents. Their run lengths can be represented with variable-length codes rather than fixed-size integers.\n\nTransform-based compression\n\nRLE is often one stage in a larger compression pipeline. In common JPEG coding processes, quantized AC coefficients are scanned in an order that often groups zeros together. The coding represents runs of zeros together with information about subsequent nonzero coefficients, using special symbols for particular cases. It is not simply RLE applied directly to pixels.\n\nRLE can also be combined with Huffman coding or arithmetic coding to compress the resulting counts and symbols. These methods exploit different forms of redundancy: RLE captures consecutive repetition, while entropy coding assigns representations according to symbol probabilities.\n\nDatabases and masks\n\nIn a database, a column containing many consecutive equal values can be represented by values and run lengths or run boundaries. Sorting may improve compression by grouping equal values, although sorting changes row order and may require additional structures to preserve relationships.\n\nSome operations can work directly on encoded runs. Counting matching values, for example, may require summing run lengths rather than expanding every record. Benefits depend on the operation and the number of runs.\n\nIn image segmentation, binary masks can be stored as alternating background and foreground run lengths. The representation must specify image dimensions, traversal order, and the initial value to reconstruct the mask correctly."
    },
    {
      "heading": "Limitations and implementation concerns",
      "text": "Dependence on local repetition. RLE does not efficiently capture repeated phrases separated by other data, nor general statistical patterns without adjacent equal values.\n\nLimited random access. Locating an arbitrary position may require accumulating run lengths from the beginning. Prefix sums, checkpoints, or a database index can accelerate access at the cost of extra storage.\n\nSensitivity to representation. Byte-level, pixel-level, and record-level RLE can produce very different results. The definition of equality and the unit being encoded are part of the scheme.\n\nParsing and resource limits. Decoders must distinguish literal values from control fields and reject malformed or truncated records. Untrusted counts can cause excessive output allocation, integer overflow, or writes beyond an output buffer. Implementations therefore need explicit bounds on both encoded input and expanded output.\n\nLosslessness depends on the whole pipeline. RLE itself preserves its input exactly. When it follows a lossy transformation, as in many JPEG workflows, it preserves the transformed symbols rather than restoring information discarded earlier."
    }
  ],
  "links": [
    "lossless-data-compression",
    "bit",
    "byte",
    "pixel",
    "algorithm",
    "pseudocode",
    "time-complexity",
    "data-compression",
    "jpeg",
    "huffman-coding",
    "arithmetic-coding",
    "database",
    "image-segmentation",
    "database-index",
    "integer-overflow"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}