Predict the output
What does this print?
from bisect import bisect_left
tails: list[int] = []
for v in [10, 9, 2, 5, 3, 7, 101, 18]:
k = bisect_left(tails, v)
if k == len(tails):
tails.append(v)
else:
tails[k] = v
print(len(tails), tails)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 4 [2, 3, 7, 18]
Right: length 4 (for example 2, 3, 7, 18), and tails holds the smallest ending of each length.
Keeping the smallest tail for each length leaves the most room for later values, which is why replacing is safe.
Why not the others?
- B 4 [2, 5, 7, 101]. Later values replace 5 with 3 and 101 with 18.
- C 3 [2, 3, 7]. 101 and then 18 extend it to length 4.