</>EmbeddedInterview

Compress a string with run-length encoding (aaabb → a3b2).

Easy"Coding: Memory & String Functions"
#include <stdio.h>
#include <string.h>

/* returns 0 on success, -1 if out is too small */
int rle_compress(const char *in, char *out, size_t out_size)
{
    size_t w = 0;
    for (size_t i = 0; in[i]; ) {
        size_t j = i;
        while (in[j] == in[i]) j++;                     /* run [i, j) */
        int n = snprintf(out + w, out_size - w, "%c%zu", in[i], j - i);
        if (n < 0 || (size_t)n >= out_size - w) return -1;
        w += (size_t)n;
        i = j;
    }
    if (w >= out_size) return -1;
    out[w] = '\0';
    return 0;
}
/* "aaabbc" -> "a3b2c1" */

Points: walk runs, append character + count; check the output buffer size (counts can be several digits); the "compressed" string can be longer than the input ("abc" → "a1b1c1"), so many versions return the original when compression does not help.