Python 0674.py
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
if len(nums) <= 1:
return len(nums)
result = 1
current = 1
seed = nums[0]
for i in range(1, len(nums)):
if nums[i - 1] < nums[i]:
current += 1
else:
result = max(result, current)
current = 1
seed = nums[i]
return max(result, current) # don't forget about the last subsequence ...
Difficulty
and has an acceptance rate of about 52% (600k+ submissions).
Typical patterns to solve this problem:
- Array
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of finding the length of the longest continuous increasing subsequence (LCIS) within a list of integers. It follows a straightforward linear scan, maintaining two counters: one for the length of the current increasing run and another for the best length observed so far. The algorithm gracefully handles trivial inputs, such as empty or single-element lists, and correctly updates the result when the scan reaches the end of the array.
Initialization and Early Return
The function begins by checking the size of the input list. If the list contains zero or one element, the length of the LCIS is trivially the size of the list itself, and the function returns immediately.
if len(nums) <= 1:
return len(nums)
This guard clause eliminates unnecessary work for degenerate cases and ensures that subsequent logic can safely assume at least two elements are present.
State Variables
Two integer variables are introduced to track progress:
resultstores the maximum length found so far and is seeded with1, reflecting the minimum possible LCIS length when the list is non-empty.currentrecords the length of the ongoing increasing segment, also starting at1.
A third variable, seed, is assigned the first element of the list. While seed is not used in the core comparison, it is updated whenever a new segment begins, effectively remembering the first value of the current run.
result = 1
current = 1
seed = nums[0]
Main Loop - Detecting Increases
The core of the algorithm iterates from the second element to the end of the list. For each position i, it compares the current element with its predecessor:
- If the predecessor is strictly smaller, the increasing run continues, and
currentis incremented. - Otherwise, the run terminates. At this point
resultis updated with the larger of its current value andcurrent. Thencurrentis reset to1to start counting a new run, andseedis refreshed to the current element.
for i in range(1, len(nums)):
if nums[i - 1] < nums[i]:
current += 1
else:
result = max(result, current)
current = 1
seed = nums[i]
The conditional nums[i - 1] < nums[i] captures the strict increase requirement, thereby excluding equal or decreasing transitions from the current subsequence.
Final Result Consolidation
After the loop finishes, the algorithm performs a final comparison between result and current. This step is essential because the longest increasing segment may end at the last element, in which case the loop’s else-branch would not have executed to update result.
return max(result, current) # don't forget about the last subsequence ...
The comment emphasizes the necessity of this final check.
Edge Cases Handled
The code explicitly addresses several boundary conditions:
- An empty list returns
0because the early return clause evaluateslen(nums) <= 1. - A single-element list returns
1, reflecting that a solitary element forms an LCIS of length one. - A list where every adjacent pair is decreasing or equal triggers the else-branch on each iteration, resetting
currenteach time and leavingresultat its initial value of1. - A list that ends with the longest increasing run benefits from the final
maxcall, ensuring that the tail segment is considered even without a terminating decrease.
Performance Optimizations
The implementation achieves efficiency through several deliberate choices:
- The early return for short lists prevents unnecessary allocation of loop variables and avoids entering the main scanning logic when the answer is already known.
- The algorithm processes the input in a single pass, updating counters on the fly without auxiliary data structures, thereby keeping the memory footprint minimal.
- The use of
maxonly when a run ends (and once more at the end) reduces the number of function calls compared to evaluating it on every iteration. - By reusing the same integer variables throughout the scan, the code avoids repeated object creation, which can be beneficial in tight loops.
Overall, the solution delivers a concise and effective approach to determining the length of the longest continuous increasing subsequence, handling edge conditions cleanly and employing straightforward optimizations to maintain low overhead.
ELI5 - Simplified Explanation
Imagine looking at a line of toy blocks arranged in a row. Each block has a number on it. The goal is to walk down the line and count how many blocks are in a row where each new block is bigger than the one before it.
Think of the computer as a little helper standing at the start of the line. Two buckets are held to keep track of the work. One bucket holds the longest stretch of growing blocks seen so far. The other bucket holds the count for the stretch currently being walked.
The helper moves from one block to the next one by one. If the new block is bigger than the last one, the helper adds one to the current count. It is like climbing a small staircase where each step goes up. If the next block is smaller or the same, the climbing stops. The helper checks if the current staircase was the longest one found so far and saves that number in the first bucket. Then the helper starts the clock over to begin counting a new staircase from the current spot. This continues until the end of the line of blocks is reached.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | PHP | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | Python | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| lzl124631x | C++ | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fengvyi | C++ | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | Python | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| lzl124631x | C++ | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 673: Number of Longest Increasing Subsequence
- problem 727: Minimum Window Subsequence
- problem 1446: Consecutive Characters
- problem 2407: Longest Increasing Subsequence II
Solved On The Same Day
- problem 705: Design HashSet
- problem 706: Design HashMap
- problem 733: Flood Fill
- problem 747: Largest Number At Least Twice of Others
- problem 748: Shortest Completing Word
- problem 486: Predict the Winner
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality