Longest Increasing Subsequence solution explained

The Longest Increasing Subsequence of a list is the longest run of values you can pick, keeping their original order and skipping any you like, where each value is strictly larger than the one before. The classic O(n²) answer stores, for each position, the longest such run ending there. The faster O(n log n) answer keeps a sorted array of the smallest possible tail for every run length and updates it with binary search.

By Published 7 min read

The problem, restated

Picture a list of daily step counts. You want the longest stretch of days, not necessarily consecutive, on which each chosen day beats the previous chosen day. Order matters, gaps are fine, ties do not count as an increase. Return how many days that stretch contains. A subsequence differs from a subarray here: a subarray must be contiguous, a subsequence may skip.

Examples written for this page
ListAnswerOne longest run
[4, 9, 2, 5, 3, 7, 11, 6]42, 3, 7, 11
[3, 10, 4, 11, 5, 6]43, 4, 5, 6
[8, 7, 5, 1]1Any single value
[6, 6, 6]1Equal values are not an increase
[]0Nothing to pick
Examples written for this page. Scroll sideways on a small screen.

Why interviewers like it

It has two good answers at two levels of difficulty. Most candidates can reach the quadratic table with some prompting, and it shows whether you can define a subproblem cleanly. The faster version tests whether you can find a monotonic structure hidden in the data and justify a greedy replacement. Interviewers rarely expect you to invent the faster idea cold, but they often ask whether you know a better bound and can explain why it works.

Follow-ups

  • Return the subsequence, not only its length. Store a parent index for each position and walk back from the best end.
  • Allow equal neighbors (non-decreasing). In the tails version, search for the first value strictly greater than x instead of the first value at least x.
  • Count how many longest runs exist. Track a count next to each length in the quadratic table and add counts when lengths tie.
  • Nesting boxes or envelopes in two dimensions. Sort by width ascending and, for equal widths, height descending, then run this algorithm on heights.

Brute force

Each element is either in or out, so there are 2^n subsets. Check each for being strictly increasing and keep the longest. That works for a dozen elements and nothing larger. It is still worth one sentence in an interview, because it frames what the faster methods are avoiding.

The O(n²) table

Define best[i] as the length of the longest increasing run that ends exactly at position i. A run ending at i either is just that one value, or extends a run ending at some earlier j with a smaller value. So best[i] is 1 plus the largest best[j] over all j before i with nums[j] less than nums[i]. The answer is the largest entry, not the last one, because the longest run can end anywhere.

def lis_length_quadratic(nums):
    if not nums:
        return 0
    best = [1] * len(nums)  # best[i]: longest increasing run ending at i
    for i in range(len(nums)):
        for j in range(i):
            if nums[j] < nums[i] and best[j] + 1 > best[i]:
                best[i] = best[j] + 1
    return max(best)
Python: quadratic dynamic programming on run length ending at each index.

Adding a parent array to the same loops gives the subsequence itself. Whenever best[i] improves through j, remember j. Start from the index with the largest best value and follow parents back to the beginning.

def lis_sequence(nums):
    n = len(nums)
    if n == 0:
        return []
    best, parent = [1] * n, [-1] * n
    for i in range(n):
        for j in range(i):
            if nums[j] < nums[i] and best[j] + 1 > best[i]:
                best[i], parent[i] = best[j] + 1, j
    i = max(range(n), key=lambda k: best[k])
    picked = []
    while i != -1:
        picked.append(nums[i])
        i = parent[i]
    return picked[::-1]
Python: one longest increasing subsequence, rebuilt from parent links.

The O(n log n) tails array

Keep a list called tails, where tails[k] is the smallest value that can end an increasing run of length k + 1 among the elements seen so far. A smaller tail is always at least as useful as a larger one, because more future values can extend it. That list is always sorted. For each new value x, find the first slot whose tail is at least x. If there is none, x extends the longest run, so append it. Otherwise x becomes a better tail for that length, so overwrite the slot. The final length of tails is the answer.

from bisect import bisect_left

def lis_length(nums):
    tails = []  # tails[k]: smallest last value of an increasing run of length k + 1
    for x in nums:
        k = bisect_left(tails, x)
        if k == len(tails):
            tails.append(x)
        else:
            tails[k] = x
    return len(tails)
Python: tails with bisect_left. O(n log n) time, O(n) memory.
function lengthOfLIS(nums) {
  const tails = [];
  for (const x of nums) {
    let lo = 0;
    let hi = tails.length;
    while (lo < hi) { // first slot whose tail is >= x
      const mid = (lo + hi) >> 1;
      if (tails[mid] < x) lo = mid + 1;
      else hi = mid;
    }
    tails[lo] = x; // appends when lo equals tails.length
  }
  return tails.length;
}
JavaScript: the same idea with a hand-written lower-bound search.

Trace [4, 9, 2, 5, 3, 7, 11, 6]. tails grows as [4], [4, 9], then 2 replaces 4, 5 replaces 9, 3 replaces 5, giving [2, 3]. Then 7 and 11 append, giving [2, 3, 7, 11]. Finally 6 replaces 7, leaving [2, 3, 6, 11]. The length 4 is correct, but 2, 3, 6, 11 is not a real subsequence because 6 comes after 11 in the input. That is the point to say out loud: tails tracks the best ending for each length, not one specific run.

Why lower bound and not upper bound? With bisect_left, an x equal to an existing tail replaces it instead of appending, so equal values never lengthen the run. That is exactly the strictly increasing rule. Switching to bisect_right lets equal values append and gives the non-decreasing version.

Complexity

Time and memory of each approach on a list of length n
ApproachTimeExtra memoryGives the sequence?
All subsetsO(2^n · n)O(n)Yes
Quadratic tableO(n²)O(n)Yes, with parent links
Tails with binary searchO(n log n)O(n)Length only, unless you also store indexes and parents
Time and memory of each approach on a list of length n. Scroll sideways on a small screen.

Edge cases

  • The empty list returns 0.
  • All values equal returns 1.
  • A strictly decreasing list returns 1, and a strictly increasing one returns its full length.
  • Negative numbers and duplicates mixed together, to check the strict comparison.

Mistakes that cost points

  • Returning best[n - 1] instead of the maximum over all positions.
  • Using less-than-or-equal in the comparison, which counts ties as increases.
  • Using upper bound in the tails search for the strict version.
  • Presenting the final tails array as the answer sequence.
  • Confusing this with the longest increasing contiguous run, which a single linear scan solves.

How to explain it out loud

Fictional example

Two levels of answer
Candidate
I will define best of i as the longest strictly increasing run that ends at index i. It is one, plus the best value among earlier smaller elements. That is n squared and I can add parent links if you want the values.
Interviewer
Can you do better?
Candidate
Yes. I keep, for each run length, the smallest tail seen so far. Those tails stay sorted, so each new number does a lower-bound search and either extends the longest run or lowers one tail. That is n log n. The array only tracks lengths, so I would not return it as the subsequence.

Longest Common Subsequence is the two-list cousin: instead of one list against itself, it compares two sequences and fills a grid. Word Break uses the same look-back over earlier positions, on text. LIS is in fact the LCS of a list and its sorted, deduplicated copy, which is a nice fact to mention if the interviewer asks how the two relate.

Practicing with Natively

Practice the jump from the quadratic table to the tails array until you can justify the replacement step without notes. In a practice session, Natively on Mac or Windows can read the problem from a screenshot and suggest an approach you can check your reasoning against, and the saved transcript shows whether you explained why tails is not a real subsequence. More on the AI interview assistant.

Questions people ask

How do you find the longest increasing subsequence?

For an O(n²) answer, compute for each index the longest strictly increasing run ending there, using earlier smaller values. For O(n log n), keep the smallest tail for each run length and update it with a lower-bound binary search.

What is the time complexity of longest increasing subsequence?

The table method is O(n²) time. The tails array with binary search is O(n log n). Both use O(n) extra memory.

Is the tails array the actual increasing subsequence?

No. Its length equals the answer, but its values can come from different runs and may be out of input order. Use parent links to rebuild a real subsequence.

How do you handle non-decreasing instead of strictly increasing?

In the tails method, search for the first tail strictly greater than the new value (upper bound) instead of the first tail at least as large (lower bound). In the table method, compare with less-than-or-equal.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP