Sub topic 8
Strict vs Non-Decreasing: bisect_left vs bisect_right
This chapter assumes you already know the O(n log n) tails-array algorithm from the previous chapters. You should also know what Python's bisect module returns, and be able to read the parent-pointer reconstruction code. The topic here is one decision that is easy to get wrong: what the algorithm does when two values are equal.
Two Problems That Look the Same
A sequence is strictly increasing if every element is greater than the one before it: 1, 2, 5. It is non-decreasing if every element is greater than or equal to the one before it: 1, 2, 2, 5. On data with no repeated values, the two problems have the same answer. With repeated values, they can differ by a lot.
Take [2, 2, 2]. Its longest strictly increasing subsequence has length 1, because no element is greater than another. Its longest non-decreasing subsequence has length 3, because the whole array qualifies.
Problem statements don't always say which one they mean. "Increasing" in competitive programming usually means strict. "Sorted" or "ascending" in data-cleaning tasks often allows ties. Settle this before you write any code.
The Change in the O(n^2) DP
The quadratic dynamic program shows the difference clearly. Element a[j] can come before a[i] in the subsequence only if the comparison allows it:
| Variant | Condition for `a[j]` to precede `a[i]` |
|---|---|
| Strictly increasing | `a[j] < a[i]` |
| Non-decreasing | `a[j] <= a[i]` |
def lis_length_quadratic(a, strict=True):
if not a:
return 0
dp = [1] * len(a)
for i in range(len(a)):
for j in range(i):
ok = a[j] < a[i] if strict else a[j] <= a[i]
if ok and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
return max(dp)
print(lis_length_quadratic([1, 3, 3, 2, 3], strict=True)) # 3
print(lis_length_quadratic([1, 3, 3, 2, 3], strict=False)) # 4In the O(n log n) version the same choice moves into the binary search, and it is harder to see there.
Why the Bisect Bound Encodes the Comparison
Recall the invariant: tails[k] is the smallest value that can end a valid subsequence of length k + 1. When a new element x arrives, you ask: what is the longest subsequence that x can extend?
- Strict:
xcan extend a subsequence whose tail is< x. The number of tails strictly less thanxis exactly whatbisect_left(tails, x)returns. - Non-decreasing:
xcan extend a subsequence whose tail is<= x. The number of tails less than or equal toxis exactly whatbisect_right(tails, x)returns.
In both cases, the returned index i is the length of the longest subsequence x can extend. So x becomes a candidate tail for length i + 1, which is slot tails[i]. If i == len(tails), then x extends the longest subsequence so far and you append it. Otherwise tails[i] is the first tail that x cannot extend, so it is greater than x (non-decreasing case) or at least x (strict case). Writing x there keeps the value the same or makes it smaller, so the invariant still holds.
The array also has a slightly different shape in each case. In the strict version, tails is strictly increasing. In the non-decreasing version, tails is only non-decreasing and can hold repeated values such as [1, 3, 3]. Both are sorted, so binary search works in both.
Tracing Both on the Same Input
Run both versions on [1, 3, 3, 2, 3].
| Step | x | Strict: index | Strict: tails | Non-decr.: index | Non-decr.: tails |
|---|---|---|---|---|---|
| 1 | 1 | 0 | [1] | 0 | [1] |
| 2 | 3 | 1 | [1, 3] | 1 | [1, 3] |
| 3 | 3 | 1 | [1, 3] | 2 | [1, 3, 3] |
| 4 | 2 | 1 | [1, 2] | 1 | [1, 2, 3] |
| 5 | 3 | 2 | [1, 2, 3] | 3 | [1, 2, 3, 3] |
The two runs split at step 3. Under the strict rule, the second 3 cannot follow the first, so bisect_left sends it to the slot the first 3 already holds, and the length stays at 2. Under the non-decreasing rule, bisect_right looks past the existing 3 and appends. The final lengths are 3 (1, 2, 3) and 4 (1, 3, 3, 3).
from bisect import bisect_left, bisect_right
def lis_length(a, strict=True):
find = bisect_left if strict else bisect_right
tails = []
for x in a:
i = find(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)
print(lis_length([1, 3, 3, 2, 3], strict=True)) # 3
print(lis_length([1, 3, 3, 2, 3], strict=False)) # 4
print(lis_length([2, 2, 2], strict=True)) # 1
print(lis_length([2, 2, 2], strict=False)) # 3Reconstruction Uses the Same Switch
The O(n log n) reconstruction from the previous chapter needs only one change: the bisect function. The parent of element i is still the index stored in tails_idx[k - 1], the tail of the subsequence that x extends.
from bisect import bisect_left, bisect_right
def lis_sequence(a, strict=True):
find = bisect_left if strict else bisect_right
tails_val = []
tails_idx = []
parent = [-1] * len(a)
for i, x in enumerate(a):
k = find(tails_val, x)
if k > 0:
parent[i] = tails_idx[k - 1]
if k == len(tails_val):
tails_val.append(x)
tails_idx.append(i)
else:
tails_val[k] = x
tails_idx[k] = i
seq = []
i = tails_idx[-1] if tails_idx else -1
while i != -1:
seq.append(a[i])
i = parent[i]
return seq[::-1]
print(lis_sequence([1, 3, 3, 2, 3], strict=True)) # [1, 2, 3]
print(lis_sequence([1, 3, 3, 2, 3], strict=False)) # [1, 3, 3, 3]Note that find must search tails_val, the values, and not tails_idx. Searching the index list by mistake is a common bug. It happens to work on some inputs, because indices also increase in some cases.
Decreasing Variants by Negation
Problems sometimes ask for the longest decreasing subsequence instead. You don't need new code. Negate the values: a is strictly decreasing exactly when -a is strictly increasing, and non-increasing exactly when -a is non-decreasing.
| Wanted subsequence | Transform | Bound |
|---|---|---|
| Strictly increasing | none | `bisect_left` |
| Non-decreasing | none | `bisect_right` |
| Strictly decreasing | negate values | `bisect_left` |
| Non-increasing | negate values | `bisect_right` |
a = [5, 4, 4, 3, 6]
print(lis_length([-x for x in a], strict=True)) # 3 (5, 4, 3)
print(lis_length([-x for x in a], strict=False)) # 4 (5, 4, 4, 3)Negation works for numbers. For strings or other non-numeric keys, use a[::-1] instead. A decreasing subsequence of a is an increasing subsequence of the reversed array, and the strict or non-strict rule carries over unchanged.
Turning One Variant into the Other
Sometimes you only have a strict implementation, for example a library function or a Fenwick-tree version that does a strict "best value below this rank" query. You can still compute the non-decreasing answer. Pair each value with its index and run the strict algorithm on the pairs:
pairs = [(x, i) for i, x in enumerate([1, 3, 3, 2, 3])]
print(lis_length(pairs, strict=True)) # 4This works because a subsequence always picks indices in increasing order. Two tuples (x, i) and (y, j) with i < j satisfy (x, i) < (y, j) exactly when x < y, or x == y. That is the same as x <= y, so strictly increasing pairs correspond to non-decreasing values. Every pair is distinct, so ties never reach the comparison.
You can't go the other way as easily. To make a non-decreasing routine behave strictly on integers, you would have to break ties so that equal values cannot follow each other. Pairing each value with its negated index, (x, -i), does that: a later copy of the same value compares as smaller.
Edge Cases and Gotchas
- Empty input. Both bounds return 0 on an empty
tails, and the loop never runs, so the length is 0. The reconstruction returns[]becausetails_idxis empty. - Float noise. Values such as
0.1 + 0.2and0.3are not equal in floating point, so a "tie" can quietly become a strict increase. Round or quantize first if the data is measured. - NaN.
float('nan')compares false with everything, which breaks the sorted invariant without any error. Filter NaN values out before running the algorithm. - Equal keys after sorting. Problems that first sort records and then run LIS, such as nesting envelopes in the next chapter, need equal-key ties handled in the sort order as well as in the bisect bound. The two choices must agree.
- Counting and Fenwick variants. The counting DP and Fenwick-tree versions in later chapters have their own comparison:
<versus<=, or querying rankr - 1versus rankr. Make that choice with the same care as the bisect bound.
Exercise
Trace lis_length([4, 4, 1, 4, 2, 4], strict=False) and give the final tails array and the returned length. Then give the strict result.
Show answer
With bisectright: x=4 → [4]; x=4 → index 1, [4, 4]; x=1 → index 0, [1, 4]; x=4 → index 2, [1, 4, 4]; x=2 → index 1, [1, 2, 4]; x=4 → index 3, [1, 2, 4, 4]. Length 4 (for example 4, 4, 4, 4 or 1, 2, 4, 4). With bisectleft the final tails is [1, 2, 4], so the strict length is 3 (1, 2, 4).
Exercise
A colleague computes the longest non-increasing subsequence with lis_length([-x for x in a], strict=True). For which inputs does this give the wrong answer, and what is the fix?
Show answer
It is wrong whenever the answer depends on repeated values, for example a = [3, 3, 3], where it returns 1 instead of 3. Non-increasing allows ties, so after negation the problem is non-decreasing: use strict=False, which means bisect_right.
Exercise
Explain why pairing each value with its index, (x, i), and running the strict algorithm gives the longest non-decreasing subsequence length.
Show answer
A subsequence uses indices in increasing order. For i < j, the tuple comparison (x, i) < (y, j) holds exactly when x < y, or x == y (because i < j breaks the tie). That is the condition x <= y. So strictly increasing pairs are exactly non-decreasing values, and the strict LIS of the pairs equals the non-decreasing LIS of the values.