Number of Longest Increasing Subsequence solution explained
Number of Longest Increasing Subsequence asks how many different strictly increasing subsequences reach the maximum possible length. Keep two values per position, the longest run ending there and how many runs achieve it: a longer run replaces the count, an equal one adds to it. That is O(n²); a Fenwick tree over sorted values that stores (length, count) pairs brings it to O(n log n).
By Evin JohnPublished 9 min read
The problem, in plain terms
Pick some positions from an array, keep them in their original order, and read off the values. If every value is strictly larger than the one before, you have an increasing subsequence. Some of those are as long as possible. The question is how many such longest ones there are. Two subsequences count as different if they use different positions, even if the values read the same.
Case A: [3, 1, 4, 2, 5]
longest length: 3
the runs: 3 4 5 | 1 4 5 | 1 2 5
answer: 3
Case B: [7, 7, 7] longest length 1, three ways answer: 3
Case C: [6, 5, 4, 3] longest length 1, four ways answer: 4Questions worth asking: is increasing strict? (Yes here; equal values do not chain.) Is the input empty allowed, and what then? (Return 0.) How big can the count get? It can grow exponentially with n, so ask whether the answer is promised to fit in 32 bits or should be taken modulo something.
Why interviewers like it
Most candidates can find the length of the longest increasing subsequence. This version checks whether you understand the DP well enough to carry a second quantity through it correctly. The tie rule (add on equal, replace on longer) is short, but getting the update order wrong, or summing only at the last index, produces answers that look plausible on small tests and fail on bigger ones.
Brute force: enumerate every subsequence
Generate all 2^n subsets of positions, keep the strictly increasing ones, and tally how many share the top length. It is exponential, so it is only a test oracle, but it states the definition precisely and was used to check every version below.
def count_longest_brute(nums):
best_len, ways = 0, 0
for mask in range(1, 1 << len(nums)):
picked = [nums[i] for i in range(len(nums)) if mask >> i & 1]
if all(picked[k] < picked[k + 1] for k in range(len(picked) - 1)):
if len(picked) > best_len:
best_len, ways = len(picked), 1
elif len(picked) == best_len:
ways += 1
return waysO(n²) DP: a length and a count per position
Every increasing subsequence ending at i is some increasing subsequence ending at an earlier j with nums[j] < nums[i], plus nums[i] itself, or nums[i] alone. So for each i, look at every such j. If length[j] + 1 is longer than what i has, i gets that length and inherits exactly count[j] ways. If it ties, the ways from j are another family of runs of the same length, so they are added. When the loop ends, find the largest length and add up the counts of every position that has it.
def count_longest(nums):
n = len(nums)
length = [1] * n
count = [1] * n
for i in range(n):
for j in range(i):
if nums[j] < nums[i]:
if length[j] + 1 > length[i]:
length[i] = length[j] + 1
count[i] = count[j]
elif length[j] + 1 == length[i]:
count[i] += count[j]
top = max(length, default=0)
return sum(c for l, c in zip(length, count) if l == top)index value length count from
0 3 1 1 (alone)
1 1 1 1 (alone)
2 4 2 2 3 and 1, both length 1
3 2 2 1 1
4 5 3 3 4 (2 ways) + 2 (1 way)
top length 3, only index 4 has it: answer 3In C++ use a 64-bit counter. A pattern like 2, 1, 4, 3, 6, 5 doubles the count with every pair, so a 32-bit int can overflow on modest inputs unless the problem guarantees the answer fits. Python integers grow as needed; JavaScript numbers lose exactness above 2^53, so use BigInt there if counts may get large.
#include <algorithm>
#include <vector>
long long countLongest(const std::vector<int>& nums) {
const int n = static_cast<int>(nums.size());
std::vector<int> length(n, 1);
std::vector<long long> count(n, 1);
int top = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[j] >= nums[i]) continue;
if (length[j] + 1 > length[i]) {
length[i] = length[j] + 1;
count[i] = count[j];
} else if (length[j] + 1 == length[i]) {
count[i] += count[j];
}
}
top = std::max(top, length[i]);
}
long long total = 0;
for (int i = 0; i < n; ++i)
if (length[i] == top) total += count[i];
return total;
}O(n log n): a Fenwick tree of (length, count)
The inner loop asks one question: among earlier values strictly below nums[i], what is the best length and how many ways reach it? That is a prefix query over values. Compress the values to ranks 1..k, then keep a Fenwick (binary indexed) tree where each node stores a (length, count) pair. Combining two pairs keeps the longer length, or adds the counts when lengths tie. Query the prefix of ranks below nums[i], extend by one, and write the result at nums[i]'s rank. Equal values are safe because the query stops one rank short, so they never chain.
def count_longest_fast(nums):
ranks = {v: r + 1 for r, v in enumerate(sorted(set(nums)))}
size = len(ranks)
best = [0] * (size + 1) # best length stored at each tree node
ways = [0] * (size + 1) # number of runs reaching that length
def merge(l1, c1, l2, c2):
if l1 > l2:
return l1, c1
if l2 > l1:
return l2, c2
return l1, c1 + c2
def query(r): # best (length, count) over ranks 1..r
l, c = 0, 0
while r > 0:
l, c = merge(l, c, best[r], ways[r])
r -= r & -r
return l, c
def update(r, l, c):
while r <= size:
best[r], ways[r] = merge(best[r], ways[r], l, c)
r += r & -r
for v in nums:
l, c = query(ranks[v] - 1)
update(ranks[v], l + 1, c if l > 0 else 1)
return query(size)[1]This is the version to offer when the interviewer asks for better than quadratic, not the one to lead with. Say that the O(n²) DP is the core idea and the tree only speeds up its inner loop. A segment tree works the same way if that is the structure you know better.
Complexity summary
| Approach | Time | Extra memory | Note |
|---|---|---|---|
| Every subsequence | O(2^n × n) | O(n) | Test oracle |
| Length and count per position | O(n²) | O(n) | Expected answer |
| Fenwick tree over value ranks | O(n log n) | O(n) | Follow-up for large n |
Edge cases to try
- Empty array: return 0, and make sure max() has a default.
- All values equal: longest length is 1, and the count is n.
- Strictly decreasing: also length 1 and count n.
- Strictly increasing: exactly one longest run.
- Several positions tie for the top length, like [1, 3, 2]: the answer sums both.
- Many repeats such as [1, 2, 2, 3, 3]: each 3 extends either 2, so the count is 4.
Mistakes to avoid
- Returning the count at the last index only, or at the first index that reached the top length.
- Adding counts on a longer length instead of replacing them.
- Using <= instead of < for the value comparison, which chains equal values.
- Initializing count[i] to 0, which makes every count zero.
- Running the patience-sorting length trick and trying to count from the tails list; it does not keep enough information to count.
Follow-ups
- Return the count modulo a large prime. Apply the modulus every time you add counts.
- List every longest subsequence. Possible only when the count is small; keep all predecessors per index and walk them back.
- Count non-decreasing runs instead. Change the strict comparison, and in the tree version query up to and including the value's own rank.
- Two-dimensional version. Combine this counting rule with the sort from Russian Doll Envelopes.
How to explain it out loud
Fictional example
- Candidate
- For each index I keep the longest increasing run that ends there, and how many runs reach that length.
- Candidate
- When an earlier smaller value gives me a longer run, I take its count. When it gives the same length, it is a different set of runs, so I add its count.
- Interviewer
- What do you return?
- Candidate
- The sum of counts at every index whose length equals the maximum. The longest runs can end in different places.
- Candidate
- That is O(n squared). If you want faster, the inner loop is a prefix query over values, so a Fenwick tree storing length and count pairs gets it to n log n.
Related problems
Russian Doll Envelopes is the length-only problem in two dimensions. Wiggle Subsequence keeps two DP states per position for a different rule. Largest Divisible Subset reuses the same double loop with a divisibility test. Climbing Stairs is the gentlest example of adding up ways from earlier states.
Practicing it with Natively
Counting problems are where a spoken explanation most often drifts from the code, so rehearse the tie rule out loud until it is automatic. Natively is a Mac and Windows app; during practice it can read the problem from a screenshot and suggest the length-and-count DP, and the transcript it keeps lets you check later whether you said replace and add in the right places. The LeetCode AI helper page shows how it fits into practice.
Questions people ask
How do you count the longest increasing subsequences?
For each index keep the longest increasing run ending there and the number of runs with that length. From each earlier smaller value, replace the count when the run gets longer and add to it when the length ties. Sum the counts of every index that reaches the overall maximum length.
What is the time complexity of Number of Longest Increasing Subsequence?
The standard DP is O(n²) time and O(n) memory. A Fenwick or segment tree over the sorted values, storing a (length, count) pair per node, reduces it to O(n log n).
Why not just sum the count at the last index?
The longest runs can end at different positions. Any index whose length equals the maximum contributes its count to the answer.
Can the count overflow?
Yes. The number of longest runs can grow exponentially with the array length, so use 64-bit integers in C++, BigInt in JavaScript if needed, or a modulus if the problem asks for one.
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.
