Scrivio Interview library
Dynamic programmingDynamic programmingReported 32 times · 16 min read · updated 15 November 2026

Find the length of the longest increasing subsequence of an array.

1What a longest increasing subsequence is

Picture a row of people standing in the order they arrived. You may tap some of them on the shoulder and ask them to step forward, but they must stay in their order. You want the largest group that, read from left to right, gets strictly taller at every step. You may skip anyone you like, but you may not reorder anyone. That is the whole problem, with heights replaced by numbers.

A group picked this way is called a subsequence, which means some elements of the array kept in their original order, with others skipped. It differs from a subarray, which must be one unbroken run of neighbours. Increasing means each chosen value is strictly bigger than the one before it. The question asks for the length of the longest such subsequence, often shortened to LIS.

Our example is 10, 9, 2, 5, 3, 7, 101, 18. Let us try by hand. Starting from 10, the only bigger values later are 101 and 18, which do not rise together, so we get 10, 101, length 2. Starting from 2 is better. After 2 we can take 5 or 3, then 7, then 101 or 18. So 2, 5, 7, 101 has length 4, and so do 2, 3, 7, 18 and 2, 5, 7, 18. Can we find five? Between 2 and the big values sit only 5, 3 and 7, and 5 and 3 cannot both be used, because 5 comes first and is bigger, so four is the best. The answer is 4.

PictureThe example array and one longest increasing subsequence

The marked boxes, 2, 5, 7 and 101, rise from left to right and keep their order in the array. No rising choice is longer than four.

  1. 10091225334751016187
    one answer
    2, 5, 7, 101
    another
    2, 3, 7, 18
    length
    4

    1In 10, 9, 2, 5, 3, 7, 101, 18 we may skip values but not reorder them. Picking 2, 5, 7, 101 gives four rising values, and four is the most we can get.

What to assume

Strictly increasing or allowed to stay equal?
We assume strictly, so 7, 7, 7, 7 gives 1.
The length or the subsequence itself?
The length.
Can the array be empty?
Yes, and the answer is 0.
How long can it be?
Up to 100,000 values, so a slow method will not do.

A careful candidate asks a few questions. Strictly increasing or allowed to stay equal? We assume strictly, so 7, 7, 7, 7 gives 1. The length or the subsequence itself? The length; recovering the values is a follow-up. Can the array be empty? Yes, and the answer is 0. How long can it be? If it can reach 100,000 values, a slow method will not do, and that is a hint about what the interviewer hopes to see.

If this feels hard, notice that we just solved it by hand with a simple habit: for each value, ask which earlier smaller value it could follow. The whole article turns that habit into a method.

2How to recognise a dynamic programming problem in this question

On a first reading, many of us try something greedy, meaning we make the choice that looks best right now and never revisit it. Walk the array and take each value that is bigger than the last one taken. On our example that takes 10, then skips everything until 101. Length 2. Taking the first value was a poor choice, but we could not know that when we made it.

So let us read the question slowly. The first clue is the word subsequence. At every element we face a choice, take it or skip it, and those choices pile up. Eight elements give two to the power eight, 256, ways to choose. Whenever a problem is a long chain of take or skip choices, trying them all explodes, and we need a smarter way to reuse work.

The second clue is the word longest. We want the best value over all those choices, not a list of them. Problems that ask for a best value often let us build the best answer for a big input from the best answers for smaller pieces. Here the smaller piece is natural: the best rising run that ends at an earlier element can be extended by a later, larger element.

These clues point to the dynamic programming pattern. Dynamic programming means solving a problem by writing down the best answer to each small piece once, in a table, and building bigger answers from that table instead of recomputing. The general rule to carry away is to name the small piece in one sentence, such as the best answer that ends exactly here, write how it is built from earlier pieces, and fill the table in order. If the table is too slow, look for a second kind of table that keeps less but enough.

Some patterns look similar but do not fit. A sliding window works only on unbroken runs, and a subsequence may skip elements. Sorting would destroy the order the question depends on. Greedy we have already seen fail. The final solution does use binary search, but only as a helper inside the dynamic programming idea.

3The honest first attempt, trying every subsequence

The brute force is the honest attempt anyone would make: try every possible group, keep the ones that rise, and remember the longest. It is a good start, because it is clearly correct and gives us something to check faster methods against.

How do we try every group? We give each group a number called a mask. Think of a row of eight light switches, one per position. Each switch is on if the position is chosen and off if not, and a number from 0 to 255 written in binary describes every pattern of switches exactly once. For each mask we walk the array, look only at chosen positions, and check that each value is bigger than the last one we kept.

Java
static int lisBrute(int[] a) {
int n = a.length, best = 0;
for (int mask = 0; mask < (1 << n); mask++) { // every subset of positions
int last = 0, len = 0;
boolean ok = true;
for (int i = 0; i < n && ok; i++) {
if ((mask & (1 << i)) == 0) continue; // position i is not chosen
ok = len == 0 || a[i] > last; // must strictly increase
last = a[i];
len++;
}
if (ok) best = Math.max(best, len);
}
return best;
}

Let us count on the example. There are 256 masks, and for each we walk up to eight positions, so about 256 times 8, around 2,000 steps. For n values it is 2 to the power n masks of n steps each, written O(n times 2^n). That doubles with every extra element. At n = 30 it is about 30 billion steps, and at n = 100,000 it would never finish. The space is small, just a few variables, O(1).

Where does it repeat work? Look at two masks that both choose 2, 5 and 7 and then differ later. The brute force checks 2 < 5 < 7 in both, and in dozens of other masks too. Yet everything a later element needs to know about the group so far is how long it is and what its last value is. Whether it was 2, 5, 7 or 2, 3, 7 does not matter to 101; both end in 7 and have length 3. That observation is the door to a faster method.

4Getting to the faster solution, one observation at a time

The first observation turns the waste into a table. For each index i, let dp[i] be the length of the longest rising run that ends exactly at a[i]. Why ends exactly at? Because then we know its last value, a[i], and that is all a later element needs. The run ending at a[i] is either a[i] alone, length 1, or some run ending at an earlier a[j] that is smaller than a[i], with a[i] added. So dp[i] = 1 + the largest dp[j] over earlier j with a[j] < a[i], or 1 if there is none. The answer is the largest dp[i] of all, because the best run must end somewhere.

The picture fills dp for our example. Watch the compared boxes: they are the earlier values small enough for a[i] to follow, and dp[i] is one more than the best dp among them.

Step throughFilling dp[i], the longest rising run that ends at index i

Top row: the array. Bottom row: dp[i], with a dash where it is not worked out yet. Compared boxes are the earlier values smaller than a[i], the only ones it can follow.

  1. 1092537101181-------
    i
    0
    a[i]
    10
    smaller before
    none
    dp[i]
    1
    best so far
    1

    1i = 0, value 10. Nothing comes before it, so the best rising run ending at 10 is 10 alone, and dp[0] = 1.

  2. 10925371011811------
    i
    1
    a[i]
    9
    smaller before
    none
    dp[i]
    1
    best so far
    1

    2i = 1, value 9. The only earlier value, 10, is not smaller than 9, so 9 cannot extend anything. dp[1] = 1.

  3. 109253710118111-----
    i
    2
    a[i]
    2
    smaller before
    none
    dp[i]
    1
    best so far
    1

    3i = 2, value 2. Neither 10 nor 9 is smaller than 2, so dp[2] = 1, a run of 2 on its own.

  4. 1092537101181112----
    i
    3
    a[i]
    5
    smaller before
    2
    dp[i]
    2
    best so far
    2

    4i = 3, value 5. Only 2 is smaller, and dp[2] = 1, so the run 2, 5 gives dp[3] = 1 + 1 = 2.

  5. 10925371011811122---
    i
    4
    a[i]
    3
    smaller before
    2
    dp[i]
    2
    best so far
    2

    5i = 4, value 3. Again only 2 is smaller, so the run 2, 3 gives dp[4] = 2.

  6. 109253710118111223--
    i
    5
    a[i]
    7
    smaller before
    2, 5, 3
    dp[i]
    3
    best so far
    3

    6i = 5, value 7. 2, 5 and 3 are smaller, with dp 1, 2 and 2. The best is 2, so dp[5] = 3, as in 2, 5, 7.

  7. 1092537101181112234-
    i
    6
    a[i]
    101
    smaller before
    10, 9, 2, 5, 3, 7
    dp[i]
    4
    best so far
    4

    7i = 6, value 101. Every earlier value is smaller; the largest dp among them is 3, at 7, so dp[6] = 4.

  8. 10925371011811122344
    i
    7
    a[i]
    18
    smaller before
    10, 9, 2, 5, 3, 7
    dp[i]
    4
    best so far
    4

    8i = 7, value 18. Every value except 101 is smaller. The best dp among them is 3, at 7, so dp[7] = 4 too. The answer is the largest dp, 4.

This is already a big step. Each of the n values looks back at up to n earlier values, so the time is O(n^2), 28 comparisons here, and dp takes O(n) space. For 100,000 values it is about 5 billion comparisons, still too slow. So we ask a beginner's question. When 18 looked back, it scanned seven values. Did it need all of them?

It did not. It only wanted the best run it could join, and for that a run's length and last value are enough. And among runs of the same length, the one with the smaller last value is always at least as useful, because more later values can climb on top of it. In our row of people, a group whose last person is shorter is easier to extend. So instead of one box per index, we keep one box per length. tails[k] holds the smallest last value of any rising run of length k + 1 seen so far.

Here is the fact that makes it fast. tails is always sorted from small to large. Take the best run of length 3 and drop its last value. What remains is a run of length 2 ending in something smaller, so tails[1] must be smaller than tails[2]. Because tails is sorted, we can find where a new value x belongs with binary search, which halves the range at each step instead of scanning it.

For each x we look for the first tail that is x or bigger. If there is none, x is bigger than every tail and extends the longest run, so we append it and the length grows. Otherwise x replaces that tail, because a run of that length can now end lower. A tempting mistake is to think tails holds the actual answer. It does not; it holds the best ending for each length, and only its size is the answer.

5Watching the tails array on the example

The picture runs the fast method on 10, 9, 2, 5, 3, 7, 101, 18. The eight boxes are the tails array; marked boxes are in use, and dashes are slots not used yet. The label pos shows where the binary search placed the new value, and the panel shows what Arrays.binarySearch returned and whether we extended or replaced.

Watch the size. It grows only when a value is bigger than every tail, and the values that only replace never make it shrink.

Step throughThe tails array after each value of 10, 9, 2, 5, 3, 7, 101, 18

Box k holds the smallest value a rising run of length k + 1 can end with. Boxes in use are marked; pos is where the binary search put the new value.

  1. -0-1-2-3-4-5-6-7size
    x
    not started
    size
    0
    tails in use
    []

    1Before the loop, tails has room for eight values but size is 0, so no slot is in use yet. Empty slots are shown as dashes.

  2. 100-1-2-3-4-5-6-7pos
    x
    10
    binarySearch
    -1
    pos
    0
    action
    extend
    size
    1

    2x = 10. tails is empty, so the search lands at position 0, which equals size. We extend: a run of length 1 can end in 10.

  3. 90-1-2-3-4-5-6-7pos
    x
    9
    binarySearch
    -1
    pos
    0
    action
    replace 10
    size
    1

    3x = 9. The first tail that is 9 or more is 10, at position 0. We replace it, because a run of length 1 ending in 9 is easier to grow.

  4. 20-1-2-3-4-5-6-7pos
    x
    2
    binarySearch
    -1
    pos
    0
    action
    replace 9
    size
    1

    4x = 2. Again the search finds position 0, and 2 replaces 9. The best run of length 1 now ends in the smallest value seen, 2.

  5. 2051-2-3-4-5-6-7pos
    x
    5
    binarySearch
    -2
    pos
    1
    action
    extend
    size
    2

    5x = 5. 5 is bigger than every tail, so the search lands at position 1, equal to size. We extend: a run of length 2 can end in 5.

  6. 2031-2-3-4-5-6-7pos
    x
    3
    binarySearch
    -2
    pos
    1
    action
    replace 5
    size
    2

    6x = 3. The first tail that is 3 or more is 5, at position 1. 3 replaces it, so the run 2, 3 is now our length 2 run.

  7. 203172-3-4-5-6-7pos
    x
    7
    binarySearch
    -3
    pos
    2
    action
    extend
    size
    3

    7x = 7. 7 is bigger than 2 and 3, so it lands at position 2 = size. We extend to length 3, ending in 7.

  8. 2031721013-4-5-6-7pos
    x
    101
    binarySearch
    -4
    pos
    3
    action
    extend
    size
    4

    8x = 101. Bigger than every tail, so it lands at position 3 and extends: a run of length 4 ending in 101.

  9. 203172183-4-5-6-7pos
    x
    18
    binarySearch
    -4
    pos
    3
    action
    replace 101
    size
    4

    9x = 18. The first tail that is 18 or more is 101, at position 3. 18 replaces it; the length stays 4, but the run now ends lower.

  10. 203172183-4-5-6-7size
    return
    size = 4
    tails in use
    [2, 3, 7, 18]

    10The loop has seen all eight values. size is 4, so we return 4. Notice that tails, 2, 3, 7, 18, happens to be a real answer here, but that is luck, not a rule.

Let us read the important frames back. 10, 9 and 2 all land at position 0, each replacing the last, because each is a smaller ending for a run of length 1. Then 5 is bigger than 2 and extends to length 2. The frame for 3 is the heart of the method. 3 replaces 5, which means a run of length 2 can now end in 3 instead of 5. Nothing about the length changed, but any later value bigger than 3 can now climb on.

7 and 101 extend to lengths 3 and 4. Finally 18 replaces 101. Again the length stays 4, but a future value of 50 could now extend it, which 101 would have blocked. After eight values the size is 4, the same answer the dp picture gave, as it must be.

6The complete Java program

The class holds both methods, so they can be compared on the same input. main prints the quadratic and fast answers for our example, then four more cases, and each comment shows what that line prints.

Java
import java.util.Arrays;
public class LongestIncreasingSubsequence {
// O(n^2) DP: dp[i] = length of the longest increasing subsequence that ends at a[i].
static int lisQuadratic(int[] a) {
int[] dp = new int[a.length];
int best = 0;
for (int i = 0; i < a.length; i++) {
dp[i] = 1; // a[i] on its own
for (int j = 0; j < i; j++) {
if (a[j] < a[i]) dp[i] = Math.max(dp[i], dp[j] + 1); // extend a run ending at j
}
best = Math.max(best, dp[i]);
}
return best;
}
// O(n log n): tails[k] = smallest possible last value of an increasing subsequence of length k + 1.
static int lis(int[] a) {
int[] tails = new int[a.length];
int size = 0;
for (int x : a) {
int pos = Arrays.binarySearch(tails, 0, size, x);
if (pos < 0) pos = -(pos + 1); // insertion point: first tail >= x
tails[pos] = x; // extend (pos == size) or lower a tail
if (pos == size) size++;
}
return size;
}
public static void main(String[] args) {
int[] a = {10, 9, 2, 5, 3, 7, 101, 18};
System.out.println(lisQuadratic(a) + " " + lis(a)); // 4 4
System.out.println(lis(new int[] {0, 1, 0, 3, 2, 3})); // 4
System.out.println(lis(new int[] {7, 7, 7, 7})); // 1
System.out.println(lis(new int[] {})); // 0
System.out.println(lis(new int[] {5, 4, 3, 2, 1})); // 1
}
}

Let us read lisQuadratic first, in the order it runs. dp is an array as long as a, and best starts at 0. For each i we first set dp[i] = 1, because a[i] alone is always a run. The inner loop then looks at every earlier j, and when a[j] < a[i] we try dp[j] + 1, keeping the larger. After the inner loop, best takes the larger of itself and dp[i].

Now lis, the fast method. tails has room for every value, and size says how many slots are in use, starting at 0. For each x we call Arrays.binarySearch(tails, 0, size, x), which searches only the slots in use. If x is found, it returns its index. If not, it returns a negative number, minus the insertion point minus one, a code that Java uses so the answer can never be confused with a real index. So pos = -(pos + 1) turns that code back into the insertion point, the first slot whose tail is bigger than x.

Then tails[pos] = x either writes into a fresh slot at the end, when pos equals size, or lowers an existing tail. Only in the first case do we grow size. When the loop ends, size is the length of the longest increasing subsequence.

Why is a found value handled correctly? In 7, 7, 7, 7 the first 7 extends to size 1. Each later 7 is found at index 0, so pos is 0 and we write 7 over 7, with no growth. That is right for strictly increasing runs, because an equal value cannot follow 7. main confirms it prints 1.

7How much it costs, and the cases at the edges

Let us count on the example. The quadratic method compared each i with every earlier j, 0 + 1 + ... + 7 = 28 comparisons. For n values that is about n squared over two, so O(n^2) time, with an O(n) dp array. The fast method did one binary search per value. A search over up to four tails takes at most three halvings, so about 8 times 3 steps in all. For n values it is O(log n) per value, read as order log n, the number of times n can be halved, so O(n log n) time, with an O(n) tails array.

The difference is huge at scale. For 100,000 values, n squared over two is 5 billion comparisons, while n log n is under 2 million.

Comparing the three methods
ApproachTimeExtra spaceIdea
Every subset of positionsO(n * 2^n)O(1)try every take or skip choice
dp[i] over earlier jO(n^2)O(n)best run ending at each index
tails with binary searchO(n log n)O(n)smallest ending for each length

The edge cases come out of the code without special handling. An empty array never enters the loop, so size stays 0 and we return 0. A single value extends once and returns 1. A strictly decreasing array such as 5, 4, 3, 2, 1 makes every value replace the first tail, so size stays 1. An already sorted array extends every time and returns n. And all equal values return 1, as we saw.

If the interviewer wants non-decreasing runs instead, where equal values may follow each other, one change is needed. We search for the first tail strictly bigger than x, so an equal x goes after the tails equal to it and can lengthen the run. The rest of the method is the same.

8Follow-up questions

How do you recover the subsequence itself, not just its length?

With the quadratic method it is gentle. Next to dp we keep an array parent, and whenever dp[j] + 1 improves dp[i], we set parent[i] = j. At the end we start from the index with the largest dp and follow parent back to the start, collecting values, then reverse them. On our example the largest dp is at 101, whose parent is 7, whose parent is 5, whose parent is 2, giving 2, 5, 7, 101. The fast method can do the same by storing, for each slot of tails, the index that last went there, and for each index the index in the slot before it at the time it was placed.

Why is it wrong to read the answer straight from the tails array?

Because each slot of tails is updated at a different time. Take 2, 5, 3, 1. After 2, 5 and 3, tails is 2, 3. Then 1 replaces 2, so tails becomes 1, 3. But 1 comes after 3 in the array, so 1, 3 is not a subsequence at all. The size, 2, is still correct, because a run of length 2 really exists, namely 2, 3. tails tells us the best ending for each length, not one consistent run.

Is the quadratic method ever the better choice?

Yes. It is easier to explain and to get right under pressure, and it adapts to variations such as the largest sum of an increasing subsequence, where the binary search trick does not apply directly. For a few thousand values it is fast enough, so a good plan is to present it first and then improve it with tails.

9Conclusion

We found the longest increasing subsequence by noticing that a later value needs only the length and last value of a run it joins. dp[i] gave an O(n^2) method, and a sorted tails array of the smallest ending for each length, placed by binary search, gave O(n log n). The clue to remember is a chain of take or skip choices with a best value to find: name the best answer that ends here, build it from earlier answers, then ask whether a smaller table is enough, just as a group ending on a shorter person is easier to extend.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm a few things first: strictly increasing, I return the length, and an empty array gives 0. Trying every subsequence is O(n times 2 to the n), and greedily taking bigger values fails on 10, 9, 2, 5, because the first pick blocks better ones.

Then, if they want more

The key observation is that a later value only needs the length and last value of a run. So dp[i] is the longest increasing run ending at a[i], which is one plus the best dp[j] over earlier j with a smaller value; the answer is the maximum dp, in O(n squared).

To do better, I keep tails[k], the smallest last value of any increasing run of length k plus 1. tails stays sorted, because dropping the last value of a longer run leaves a shorter run with a smaller end.

For each value x I binary search for the first tail that is at least x; if there is none, I append and the length grows, otherwise I replace that tail with x, because a lower ending is easier to extend. The final size is the answer.

That is O(n log n) time and O(n) space, and an equal value replaces rather than extends, which keeps it strictly increasing.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 32 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Find the length of the longest increasing subsequence of an array.": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-length-of-the-longest-increasing-subsequence-of-an-arra-f10907/