Problem 674

Abstract / Summary

Find the length of the longest sequence of consecutive increasing numbers in a list of integers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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 ...
17 lines | 521 bytes | submitted October 4, 2023 | GitHub   6% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 52% (600k+ submissions).

Typical patterns to solve this problem:
  • Array
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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:

  • result stores the maximum length found so far and is seeded with 1, reflecting the minimum possible LCIS length when the list is non-empty.
  • current records the length of the ongoing increasing segment, also starting at 1.

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 current is incremented.
  • Otherwise, the run terminates. At this point result is updated with the larger of its current value and current. Then current is reset to 1 to start counting a new run, and seed is 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 0 because the early return clause evaluates len(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 current each time and leaving result at its initial value of 1.
  • A list that ends with the longest increasing run benefits from the final max call, 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 max only 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.30 | σ = 0.90

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
42 links | 27 authors | 11 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

5 easy 1 medium
7 solutions   October 4, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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