Function Assignment 29 — Find the Longest Increasing Subsequence Using a Function
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Find the Longest Increasing Subsequence Using a Function

📑 On this page:
  • What an increasing subsequence is
  • Dynamic programming — the O(n²) approach
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • What a subsequence is — and why it's different from a subarray
  • The O(n²) dynamic-programming solution for the LIS problem
  • Why dp[i] means "LIS ending at index i"
  • How to reconstruct the actual subsequence, not just its length
  • How the O(n log n) binary-search improvement works in principle

What an increasing subsequence is

A subsequence of an array is any selection of its elements, in their original order, possibly skipping some. Unlike a subarray (which must be contiguous), a subsequence can have gaps. For the array [10, 9, 2, 5, 3, 7, 101, 18], valid subsequences include [10, 5, 7, 18], [2, 3, 7, 18], and [10, 9, 2]. An increasing subsequence is one where each element is strictly greater than the previous one.

The Longest Increasing Subsequence (LIS) problem asks: what's the length of the longest subsequence you can pick that's strictly increasing? For our example array, the answer is 4 — achieved by [2, 3, 7, 18], or alternatively [2, 3, 7, 101], or [2, 5, 7, 101]. Multiple subsequences can have length 4, and the problem only asks for the length (not the specific subsequence — though we can reconstruct it if needed).

LIS is a classic dynamic programming problem. The naive approach would enumerate all 2ⁿ subsequences and check each — exponential, unusable for anything beyond n = 20. The DP approach reduces this to O(n²) — for n = 10,000, that's 100 million operations, tractable. And there's an even faster O(n log n) version using binary search, which is what you'd use in practice for very large inputs.

LIS has real applications: patience sorting (a card game and algorithm), finding chains of dependencies in build systems, computing the minimum number of non-decreasing sequences to partition an array (Dilworth's theorem), and analyzing DNA sequences. It's also a favorite interview problem, because the DP solution is elegant and the O(n log n) optimization requires real insight. Understanding both is a milestone in becoming comfortable with algorithms.

💡 In one line: compute dp[i] = length of LIS ending at index i. For each i, look at all j < i with arr[j] < arr[i] — if any, extend the best such dp[j] by 1. The answer is max(dp).

An array with one possible longest increasing subsequence highlighted, showing elements that increase in value as you move right.

Dynamic programming — the O(n²) approach

The key observation: if we know the LIS ending at each earlier index, we can compute the LIS ending at the current index. For index i, the LIS ending there is:

  • 1 (the element by itself), if no earlier element is smaller.
  • dp[j] + 1 for the best j < i with arr[j] < arr[i], otherwise.

So the recurrence is: dp[i] = 1 + max(dp[j]) over all j < i with arr[j] < arr[i]. If no such j exists, dp[i] = 1. The LIS of the whole array is the maximum of all dp[i].

Here's the trace for [10, 9, 2, 5, 3, 7, 101, 18]:

i arr[i] dp[i] Reason
0101No earlier elements
1919 < 10, no valid j
2212 < 10, 9, no valid j
3525 > 2 (dp[2]=1), so dp[3]=2
4323 > 2 (dp[2]=1), so dp[4]=2
5737 > 5, 3, 2 (max dp[j]=2 at j=3,4), so dp[5]=3
61014101 > all, max dp[j]=3 at j=5, so dp[6]=4
718418 > all except 101, max dp[j]=3 at j=5, so dp[7]=4

The maximum dp value is 4, so the LIS length is 4. Which subsequence achieves it? Tracing back from dp[i] = 4 and following predecessors: for i=7 (value 18), the predecessor is j=5 (value 7, dp=3); for j=5, the predecessor is j=3 (value 5, dp=2); for j=3, the predecessor is j=2 (value 2, dp=1). So the subsequence is [2, 5, 7, 18] — length 4, strictly increasing. ✓

🎯 Key insight: dp[i] is the length of the longest increasing subsequence ending at index i. The restriction ("ending at i") is what makes the DP work — it gives a well-defined subproblem and a simple recurrence. This is the same trick as Kadane's algorithm, just applied to a harder problem.

Complete C Program

Program: find the length of the longest increasing subsequence

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

/* Function prototype */
int lisLength(const int arr[], int n);

int main(void) {
    int arr[100];
    int n;

    printf("How many elements? ");
    if (scanf("%d", &n) != 1 || n <= 0 || n > 100) {
        printf("Please enter a valid count between 1 and 100.\n");
        return 1;
    }

    printf("Enter %d integers: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &arr[i]) != 1) return 1;
    }

    printf("Longest increasing subsequence length: %d\n", lisLength(arr, n));

    return 0;
}

/* O(n^2) LIS via dynamic programming */
int lisLength(const int arr[], int n) {
    if (n == 0) return 0;

    int *dp = malloc(n * sizeof(int));
    if (!dp) return -1;

    for (int i = 0; i < n; i++) {
        dp[i] = 1;  /* each element by itself */
        for (int j = 0; j < i; j++) {
            if (arr[j] < arr[i] && dp[j] + 1 > dp[i]) {
                dp[i] = dp[j] + 1;
            }
        }
    }

    int best = 0;
    for (int i = 0; i < n; i++) {
        if (dp[i] > best) best = dp[i];
    }

    free(dp);
    return best;
}
                                    

And a version that reconstructs the actual subsequence, not just its length:

Variant: reconstruct the subsequence

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

void lisWithPath(const int arr[], int n) {
    int *dp = malloc(n * sizeof(int));
    int *parent = malloc(n * sizeof(int));
    if (!dp || !parent) { free(dp); free(parent); return; }

    int bestEnd = 0;
    for (int i = 0; i < n; i++) {
        dp[i] = 1;
        parent[i] = -1;
        for (int j = 0; j < i; j++) {
            if (arr[j] < arr[i] && dp[j] + 1 > dp[i]) {
                dp[i] = dp[j] + 1;
                parent[i] = j;
            }
        }
        if (dp[i] > dp[bestEnd]) bestEnd = i;
    }

    /* Walk back from bestEnd to build the sequence */
    int *seq = malloc(dp[bestEnd] * sizeof(int));
    int k = dp[bestEnd] - 1;
    for (int i = bestEnd; i != -1; i = parent[i]) {
        seq[k--] = arr[i];
    }

    printf("Length: %d\n", dp[bestEnd]);
    printf("Subsequence: ");
    for (int i = 0; i < dp[bestEnd]; i++) printf("%d ", seq[i]);
    printf("\n");

    free(dp);
    free(parent);
    free(seq);
}

int main(void) {
    int arr[] = {10, 9, 2, 5, 3, 7, 101, 18};
    int n = sizeof(arr) / sizeof(arr[0]);
    lisWithPath(arr, n);
    return 0;
}
                                

The parent array records, for each index, the index of its predecessor in the LIS ending at that position. After computing the DP, we walk back from the best end index, following parent pointers, and collect the sequence. The result is printed in reverse, so we walk back and fill the output array from the end.

And a version that uses the O(n log n) binary-search approach — much faster for large arrays, but more subtle:

Variant: O(n log n) LIS with binary search

#include <stdio.h>

int lisNLogN(const int arr[], int n) {
    if (n == 0) return 0;

    int *tails = malloc(n * sizeof(int));
    int len = 0;

    for (int i = 0; i < n; i++) {
        int lo = 0, hi = len;
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (tails[mid] < arr[i]) lo = mid + 1;
            else hi = mid;
        }
        tails[lo] = arr[i];
        if (lo == len) len++;
    }

    free(tails);
    return len;
}

int main(void) {
    int arr[] = {10, 9, 2, 5, 3, 7, 101, 18};
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("LIS length: %d\n", lisNLogN(arr, n));
    return 0;
}
                                

The tails array holds, at each position, the smallest possible tail of an increasing subsequence of that length. For each new element, binary search for the first tail that's not smaller, and replace it. The length of tails at the end is the LIS length. This is O(n log n) — for n=100,000, that's about 1.7 million operations vs. 10 billion for the O(n²) version. The catch is that tails is not itself the LIS — reconstructing the actual subsequence requires more bookkeeping.

Program Output

A typical run of the first program:

How many elements? 8
Enter 8 integers: 10 9 2 5 3 7 101 18
Longest increasing subsequence length: 4
                                

The LIS is 4 — achieved by [2, 5, 7, 18] or [2, 3, 7, 101] among others. The function only reports the length; if you need the specific subsequence, use the reconstruction variant.

With a strictly decreasing array:

How many elements? 5
Enter 5 integers: 5 4 3 2 1
Longest increasing subsequence length: 1
                                

When the array is sorted in decreasing order, no element is greater than any earlier element, so the LIS is just 1 (any single element). The DP correctly sets every dp[i] = 1 and returns 1.

With a strictly increasing array:

How many elements? 5
Enter 5 integers: 1 2 3 4 5
Longest increasing subsequence length: 5
                                

When the array is sorted in increasing order, the entire array is the LIS — length 5. This is the best case, and the DP computes it correctly: every dp[i] = i + 1, so dp[4] = 5.

With all duplicate elements:

How many elements? 5
Enter 5 integers: 7 7 7 7 7
Longest increasing subsequence length: 1
                                

For strictly increasing, duplicates don't count — 7 is not greater than 7. So the LIS is just 1 (any single 7). If the problem allowed non-decreasing (i.e., arr[j] <= arr[i]), the answer would be 5. The distinction between "increasing" and "non-decreasing" is important and sometimes missed in problem statements.

And the reconstruction variant:

Length: 4
Subsequence: 2 5 7 18
                                

The variant tells you both the length (4) and the actual subsequence [2, 5, 7, 18]. Notice it's one of several possible LISes — [2, 3, 7, 101] and [2, 5, 7, 101] are also valid, but the algorithm happens to find the one ending at 18. Any valid answer is correct.

Step-by-Step Explanation

Let's walk through the DP and see why it works.

1. The DP table

dp[i] is the length of the longest increasing subsequence ending at index i. Every element by itself is a subsequence of length 1, so we initialize all dp[i] = 1. Then we refine these values by looking at earlier elements.

For each i, we look at every j < i. If arr[j] < arr[i] (i.e., we can extend the LIS ending at j by appending arr[i]), then the LIS ending at i could be as long as dp[j] + 1. We take the maximum over all such j. If no j has a smaller element, dp[i] stays 1.

2. Why this is correct

Any increasing subsequence ending at i must have its second-to-last element at some position j < i. If the subsequence has length > 1, that j satisfies arr[j] < arr[i] (the subsequence is increasing). The longest such subsequence at i is therefore 1 + max(dp[j]) over all valid j. This is exactly what the recurrence computes. By induction, dp[i] is the correct LIS length ending at i.

3. Tracing the DP for our example

For arr = [10, 9, 2, 5, 3, 7, 101, 18]:

  • dp[0] = 1 (10, no predecessors).
  • dp[1] = 1 (9 — 10 is not smaller, no valid j).
  • dp[2] = 1 (2 — same, no valid j).
  • dp[3] = 2 (5 — 2 < 5, dp[2] + 1 = 2).
  • dp[4] = 2 (3 — 2 < 3, dp[2] + 1 = 2).
  • dp[5] = 3 (7 — 5 < 7, dp[3] + 1 = 3, also 3 < 7 with dp[4] + 1 = 3, max is 3).
  • dp[6] = 4 (101 — every earlier is smaller, max is dp[5] + 1 = 4).
  • dp[7] = 4 (18 — 7 < 18, dp[5] + 1 = 4; 101 is not smaller, doesn't help).

Max dp = 4. ✓

4. Finding the actual subsequence

The parent array records, for each i, which j was the predecessor used to achieve dp[i]. After computing the full DP, pick the index i* with the maximum dp[i*]. That's the last element of some LIS. Walk back through parent[i*], parent[parent[i*]], and so on, until you hit -1. The path visits the indices of the LIS, in reverse. Reverse them to get the actual subsequence.

For our example, bestEnd = 7 (value 18, dp=4). parent[7] = 5 (value 7), parent[5] = 3 (value 5), parent[3] = 2 (value 2), parent[2] = -1. Walking back: 7 → 5 → 3 → 2. The subsequence is arr[2], arr[3], arr[5], arr[7] = [2, 5, 7, 18]. ✓

5. Complexity

O(n²) time — the outer loop runs n times, and for each i, the inner loop runs i times, so the total is n(n-1)/2 = O(n²). O(n) space — the dp array (and parent if you reconstruct). This is fine for n up to about 10,000 (100 million operations, a few seconds). For larger arrays, use the O(n log n) binary-search version.

6. The O(n log n) insight

The faster version maintains an array tails where tails[k] is the smallest possible tail of any increasing subsequence of length k+1. When you see a new element, you binary search tails for the first position where the tail is ≥ arr[i], and replace it. This keeps tails sorted, and the length of tails at the end is the LIS length.

Why does this work? Because for a fixed LIS length, a smaller tail is always at least as good as a larger one — you can extend it with more future elements. So we only need to track the smallest tail per length. The tails array holds exactly those. When a new element comes, it either extends the longest chain (if it's larger than all tails) or updates the tail of some shorter chain to be smaller. Either way, the invariant is maintained.

7. Reconstructing from the O(n log n) version

The tails array alone isn't enough — it only holds the "shape" of the DP, not the actual subsequence. To reconstruct, you'd add a parallel parent array that records, for each element, which previous position preceded it in the LIS. This adds O(n) space and a bit of bookkeeping to the binary-search version. It's doable, just more complex than the O(n²) reconstruction.

8. Applications of LIS

LIS appears in many contexts:

  • Patience sorting: physically sorted cards correspond to computing the LIS via binary search — the algorithm is inspired by solitaire.
  • Minimum number of decreasing subsequences: by Dilworth's theorem, the minimum number of non-increasing subsequences needed to partition an array equals the LIS length. This is used in scheduling and packing problems.
  • Box stacking: given boxes with dimensions, find the tallest tower you can build (each box on the next is smaller in all dimensions). This reduces to LIS after sorting.
  • Longest chain problems: given pairs (a, b), find the longest chain where each pair has both coordinates strictly smaller than the next. Reduces to LIS after sorting by first coordinate.
  • Bioinformatics: aligning DNA sequences uses LIS as a subroutine.

9. Comparison with other DP problems

LIS is one of the simpler DP problems — the state is just dp[i], and the recurrence is a simple max over smaller indices. Compare with:

  • Longest common subsequence (LCS): 2D DP, state dp[i][j] for prefixes of two strings, recurrence involves more cases.
  • Edit distance: 2D DP, similar to LCS but with different recurrence. O(m×n) time.
  • Knapsack: 2D DP over items and capacity. O(n×W) time, often pseudo-polynomial.
  • Coin change: DP over amount. O(amount × n) time.

LIS is the gateway drug to dynamic programming — the state and recurrence are simple enough to grasp quickly, but the pattern generalizes to all of these harder problems. If you can explain LIS, you're ready to tackle LCS, edit distance, and knapsack with confidence.

10. Strictly vs. non-strictly increasing

Our implementation uses arr[j] < arr[i] — strictly increasing. For non-decreasing, use arr[j] <= arr[i]. This is a one-character change, but it changes the answer significantly for arrays with duplicates. For [5, 5, 5], strictly increasing gives LIS = 1, non-decreasing gives LIS = 3. Always check the problem statement to know which one is meant. "Increasing" usually means strictly, but "non-decreasing" is sometimes implied in contexts like scheduling or stock prices.

🔍 Try this: change the comparison to <= and run on [5, 5, 5]. The answer should go from 1 (strictly increasing) to 3 (non-decreasing). Then try the problem "longest bitonic subsequence" — first increasing then decreasing. It requires computing LIS from both ends and combining them. A great extension that teaches you to think about subproblems from multiple directions.

Frequently Asked Questions

1. What's the difference between a subarray and a subsequence?

A subarray must be contiguous — a run of consecutive elements. A subsequence can skip elements, as long as the order is preserved. For [1, 2, 3, 4], subarrays include [1, 2], [2, 3, 4], and [3], but not [1, 3]. Subsequences include [1, 3] (skipping 2) and [1, 2, 4] (skipping 3). The LIS problem is about subsequences (with gaps allowed), not subarrays. This distinction matters — the maximum-sum subarray problem (Kadane's) has a different solution than the maximum-sum subsequence problem (which is just the sum of positive elements).

2. Why is dp[i] "LIS ending at i" and not "LIS of the first i elements"?

Because "ending at i" is a stronger, more useful restriction. If dp[i] meant "LIS of the first i elements," then the recurrence would need to consider all possible last elements, not just arr[i]. With "ending at i," the recurrence is dp[i] = 1 + max(dp[j]) over j < i with arr[j] < arr[i] — much simpler. The tradeoff is that after computing all dp values, we need to take the maximum across all indices — because the LIS might end anywhere.

3. Why does arr[j] < arr[i] work but arr[j] <= arr[i] doesn't for strictly increasing?

If you use arr[j] <= arr[i], then equal elements can extend each other. For [5, 5, 5], each 5 could extend the previous 5, giving LIS = 3. But "strictly increasing" requires each element to be strictly greater than the previous — equal values don't count. So for strict increasing, use <; for non-decreasing, use <=. Read the problem statement carefully to know which one is meant.

4. Why does the O(n²) version use so much less memory than other DP problems?

Because the state is 1D — just dp[i]. In 2D DP problems like LCS (longest common subsequence) or edit distance, the state is dp[i][j], which requires O(m×n) space. LIS only needs O(n) space because each subproblem depends only on earlier positions in the same array. This is one reason LIS is considered a "gateway" DP problem — the state structure is simpler than 2D problems.

5. How does the O(n log n) version work?

The fast version maintains an array tails where tails[k] is the smallest possible tail of any increasing subsequence of length k+1. For each new element, binary search for the first position where tails[k] >= arr[i], and replace tails[k] with arr[i]. If no such position exists (all tails are smaller than arr[i]), append arr[i] — the LIS grows by one. The invariant is that tails remains sorted, so binary search applies. At the end, the length of tails is the LIS length. Time: O(n log n) — the outer loop is n, and each binary search is log n. Space: O(n) for tails.

6. Why isn't the O(n log n) version the default?

Because it's harder to understand and doesn't support reconstruction easily. The tails array is not itself the LIS — it's an optimized state that happens to track the correct length. Reconstructing the actual subsequence requires extra parent tracking. For n < a few thousand, the O(n²) version is fine and much clearer. Use the O(n log n) version only when n is large enough that the O(n²) version would be too slow — usually n > 10,000 or so.

💡 Tip: Once this works, try "longest common subsequence" (LCS) — it's the 2D DP problem that many people confuse with LIS. Given two strings, find the length of their longest common subsequence. The DP is similar but uses a 2D table: dp[i][j] = LCS of first i chars of one string and first j chars of the other. Different shape, same mindset. Then try edit distance (Levenshtein) — it's the same 2D structure with a different recurrence. Together, these three are the classic "intro DP" problems, and mastering them gives you a solid foundation for harder ones.

📖 Related Tutorials

  • Introduction to Functions in C
  • One Dimensional Arrays
  • Passing Arrays to Functions
  • Function Definition
  • Function Declaration
  • Previous: Find the Largest Sum Subarray
  • Next: Find the Median of Two Sorted Arrays
  • All 33 Function Assignments

Previous Topic: -->> 28. Find the Largest Sum Subarray Using a Function   ||   Next Topic: -->> 30. Find the Median of Two Sorted Arrays Using a Function


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.