Reading history

Longest Increasing Subsequence (LIS) in C: O(n²) and O(n log n)

6 min read 1 views

Find the longest increasing subsequence in C with O(n^2) dynamic programming and the O(n log n) tails method using binary search, with traces.

Given a list of numbers, the longest increasing subsequence (LIS) is the longest set of values you can pick, keeping their original order, so that each one is bigger than the one before. It describes the longest stretch of steady growth in a series of sales, prices or exam marks, even when bad months interrupt it. LIS is also a favourite interview question because it has two solutions: a simple O(n2) dynamic programming method, and a clever O(n log n) method that uses binary search.

In this lesson you will learn

  • What an increasing subsequence is
  • The O(n2) DP solution and how to rebuild the sequence
  • The O(n log n) “tails” method with binary search
  • Why the tails array is always sorted
  • Strictly increasing versus non-decreasing variants

You should know dynamic programming and binary search.

The O(n²) Dynamic Programming Solution

#include <stdio.h>

/* O(n^2) LIS: len[i] = length of the longest increasing subsequence ending at a[i] */
static int lis_quadratic(const int *a, int n, int *out) {
    int len[64], prev[64], best = 0;
    for (int i = 0; i < n; i++) {
        len[i] = 1;
        prev[i] = -1;
        for (int j = 0; j < i; j++)
            if (a[j] < a[i] && len[j] + 1 > len[i]) {
                len[i] = len[j] + 1;
                prev[i] = j;
            }
        if (len[i] > len[best]) best = i;
    }
    int k = len[best];
    for (int i = best; i != -1; i = prev[i]) out[--k] = a[i];   /* rebuild backwards */
    return len[best];
}

int main(void) {
    int a[] = {10, 22, 9, 33, 21, 50, 41, 60, 80, 3};
    int n = sizeof a / sizeof a[0], out[64];
    int len = lis_quadratic(a, n, out);
    printf("LIS length %d:", len);
    for (int i = 0; i < len; i++) printf(" %d", out[i]);
    printf("\n");

    /* Monthly sales: the longest run of months (not necessarily adjacent) with rising sales */
    int sales[] = {120, 90, 130, 140, 100, 150, 110, 160, 170, 155, 180, 175};
    len = lis_quadratic(sales, 12, out);
    printf("rising sales over %d months:", len);
    for (int i = 0; i < len; i++) printf(" %d", out[i]);
    printf("\n");
    return 0;
}

Output

LIS length 6: 10 22 33 50 60 80
rising sales over 7 months: 120 130 140 150 160 170 180
  • len[i] is the length of the longest increasing subsequence that ends at a[i]. Every element alone is a sequence of length 1.
  • For each i, look at every earlier j. If a[j] < a[i], then a[i] can extend the best sequence ending at a[j], giving len[j] + 1.
  • The answer is the largest value in len, not necessarily the last one: the final element 3 has len 1.
  • prev[i] remembers which j gave the best length, so following prev backwards from the best position rebuilds the sequence: 10, 22, 33, 50, 60, 80.
  • The two nested loops take O(n2) time, which is fine for a few thousand items.
  • For the sales data, the answer shows seven months of rising sales despite the dips in between.

The O(n log n) Tails Method

#include <stdio.h>
#include <stdlib.h>

/* O(n log n) LIS: tails[k] = smallest possible tail of an increasing subsequence of length k+1 */
static int lis_fast(const int *a, int n, int show) {
    int *tails = malloc((size_t)n * sizeof *tails);
    if (tails == NULL) return -1;
    int size = 0;
    for (int i = 0; i < n; i++) {
        int lo = 0, hi = size;                 /* binary search: first tail >= a[i] */
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (tails[mid] < a[i]) lo = mid + 1;
            else hi = mid;
        }
        tails[lo] = a[i];                      /* replace it, or extend if lo == size */
        if (lo == size) size++;
        if (show) {
            printf("read %2d -> tails:", a[i]);
            for (int k = 0; k < size; k++) printf(" %d", tails[k]);
            printf("\n");
        }
    }
    free(tails);
    return size;
}

int main(void) {
    int a[] = {10, 22, 9, 33, 21, 50, 41, 60, 80, 3};
    int n = sizeof a / sizeof a[0];
    printf("LIS length: %d\n\n", lis_fast(a, n, 1));

    /* A big test: 100,000 numbers from a simple formula */
    int big_n = 100000;
    int *big = malloc((size_t)big_n * sizeof *big);
    if (big == NULL) return 1;
    unsigned x = 12345;
    for (int i = 0; i < big_n; i++) {
        x = x * 1103515245u + 12345u;          /* small pseudo-random generator */
        big[i] = (int)(x >> 16) % 1000000;
    }
    printf("LIS of %d pseudo-random numbers: %d\n", big_n, lis_fast(big, big_n, 0));
    free(big);
    return 0;
}

Output

read 10 -> tails: 10
read 22 -> tails: 10 22
read  9 -> tails: 9 22
read 33 -> tails: 9 22 33
read 21 -> tails: 9 21 33
read 50 -> tails: 9 21 33 50
read 41 -> tails: 9 21 33 41
read 60 -> tails: 9 21 33 41 60
read 80 -> tails: 9 21 33 41 60 80
read  3 -> tails: 3 21 33 41 60 80
LIS length: 6

LIS of 100000 pseudo-random numbers: 619
  • tails[k] holds the smallest possible last value of an increasing subsequence of length k + 1 seen so far. A small tail is better, because more future numbers can extend it.
  • For each new number, binary search finds the first tail that is greater than or equal to it. If there is none, the number extends the longest sequence and tails grows. Otherwise it replaces that tail with a smaller value.
  • Watch the trace: reading 9 replaces 10, because a length-1 sequence ending in 9 is more useful than one ending in 10. Reading 21 replaces 22 for the same reason.
  • tails is always sorted, which is what makes binary search possible. Its length is the LIS length.
  • Careful: tails itself is not always a real subsequence. After reading 3 it is “3 21 33 41 60 80”, but 3 comes last in the input. Only its length is guaranteed correct. Rebuilding the sequence needs extra index arrays.
  • Each of the n numbers does one binary search, so the total time is O(n log n). The 100,000-number test runs instantly, where the O(n2) method would need about 5 billion comparisons.

Comparing the Two Methods

DP with len[]Tails + binary search
TimeO(n2)O(n log n)
MemoryO(n)O(n)
Rebuilding the sequenceEasy with prev[]Needs extra index tracking
Best forSmall inputs, learning, variantsLarge inputs, contests

Common Mistakes

  1. Returning len[n-1] instead of the maximum over all positions.
  2. Printing the tails array as the answer; only its length is reliable.
  3. Using the wrong comparison in the binary search. For strictly increasing, find the first tail >= x; for non-decreasing, find the first tail > x.
  4. Confusing LIS with the longest increasing run of adjacent elements, which a single loop solves.

Practice Exercises

Exercise 1. What is the LIS length of {5, 4, 3, 2, 1} and of {1, 2, 3, 4, 5}?

Show answer

1 and 5. A decreasing array allows only single elements; a sorted array is its own LIS.

Exercise 2. Find the fewest elements to remove so that the remaining array is strictly increasing.

Show answer

Keep the LIS and remove the rest: n - LIS. For the 10-number example, 10 − 6 = 4 removals.

Frequently Asked Questions

Is LIS related to LCS?

Yes. The LIS of an array equals the longest common subsequence of the array and a sorted copy of it with duplicates removed. That gives a third, O(n2) way to solve it.

Where is LIS used in practice?

It appears in stacking and nesting problems (such as fitting envelopes inside each other), in analysing trends in time series, and inside algorithms like patience sorting and some diff tools.

Summary

  • LIS picks the longest increasing set of values while keeping their order.
  • The DP method is O(n2) and easily rebuilds the sequence.
  • The tails method is O(n log n); its length is the answer.
  • Choose >= or > in the binary search for strict or non-strict versions.

Next: Segment Tree in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *