Python 0659.py
class Solution:
def isPossible(self, nums: List[int]) -> bool:
runs = defaultdict(list)
for n in nums:
# start new seq
if n-1 not in runs:
runs[n].append(1)
continue
# extend existing
runs[n-1].sort() # prefer to extend short seqs
runs[n].append(runs[n-1][0] + 1)
del runs[n-1][0]
if not runs[n-1]:
del runs[n-1]
for r in runs:
if min(runs[r]) < 3:
return False
return True
Difficulty
and has an acceptance rate of about 52% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Hash Table
- Heap (Priority Queue)
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 determines whether a sorted list of integers can be partitioned into one or more consecutive subsequences, each of length at least three. It processes the input in a single pass, maintaining a mapping from the last value of a subsequence to the lengths of all subsequences that currently end with that value. By always extending the shortest possible subsequence, the algorithm ensures that the minimum length constraint is respected when the input is exhausted.
Core Logic
The algorithm revolves around a dictionary named runs. Each key represents the last integer of an active subsequence, and the associated list stores the lengths of all subsequences that terminate at that integer.
runs = defaultdict(list)
Iterating Over the Input
For every integer n in the input list nums, the code decides whether to start a new subsequence or to extend an existing one.
for n in nums:
# start new seq
if n-1 not in runs:
runs[n].append(1)
continue
If there is no subsequence ending with n-1, a fresh subsequence is begun with length 1, and the loop proceeds to the next number.
Extending an Existing Subsequence
When a subsequence ending with n-1 exists, the algorithm selects the shortest such subsequence, increments its length, and moves it to the bucket keyed by n.
# extend existing
runs[n-1].sort() # prefer to extend short seqs
runs[n].append(runs[n-1][0] + 1)
del runs[n-1][0]
if not runs[n-1]:
del runs[n-1]
The sort() call guarantees that the first element of runs[n-1] is the minimal length, thereby favoring the extension of the shortest active subsequence. After the extension, the original entry for n-1 is updated by removing the consumed length; if the list becomes empty, the key itself is removed to keep the dictionary compact.
Final Validation
Once all numbers have been processed, the algorithm verifies that every remaining subsequence satisfies the length requirement of at least three.
for r in runs:
if min(runs[r]) < 3:
return False
return True
If any bucket contains a length smaller than three, the function returns False; otherwise, it returns True.
Edge Cases Handled
The code gracefully handles an empty input list. Since the loop body never executes, the final validation loop sees an empty runs dictionary, and the function returns True, which is appropriate because there are no subsequences that violate the length constraint.
When the input contains isolated numbers that cannot be linked to any existing subsequence (for example, a solitary 5 with no 4 preceding it), the algorithm creates a new subsequence of length 1. The subsequent validation step will detect this short subsequence and cause the function to return False.
Sequences with duplicate values are also accommodated. Because the input is assumed to be sorted, duplicate entries appear consecutively. Each duplicate either starts a new subsequence (if no preceding value exists) or extends an existing one, preserving the invariant that all active subsequences remain consecutive.
Gaps larger than one between numbers automatically trigger the creation of new subsequences for the numbers after the gap, as the condition n-1 not in runs will be true for the first number after any gap. The final validation ensures that any subsequence that could not be extended sufficiently is rejected.
Performance Optimizations
The implementation leverages a defaultdict(list) to avoid explicit existence checks before appending lengths, reducing overhead in the main loop. By sorting only the list associated with the current predecessor (runs[n-1]) rather than the entire dictionary, the algorithm confines the cost of ordering to the smallest necessary subset of data. This localized sorting is sufficient because only the smallest length is needed for the extension decision.
Removing consumed entries (del runs[n-1][0]) and deleting empty keys (del runs[n-1]) prevents the dictionary from retaining stale data, which keeps the memory footprint proportional to the number of active subsequences rather than the total number of processed elements. The final validation loop iterates over the remaining keys only, which at most equals the number of distinct ending values of active subsequences.
By always extending the shortest available subsequence, the algorithm minimizes the risk of leaving behind short, unextendable sequences, thereby reducing the amount of work required in the final validation step. This greedy choice aligns with the problem constraints and contributes to an efficient overall execution.
ELI5 - Simplified Explanation
Imagine having a box filled with numbered game pieces and trying to sort them into neat rows. Each row needs to have at least three pieces in numerical order, like one, two, then three.
The computer does this by going through the pieces one by one. If it finds a piece that can follow a previous number, it adds that piece to the end of an existing row. If the piece cannot fit onto a row that already exists, it starts a brand new row.
While doing this, the computer is smart enough to pick the shortest rows first so that it can make them longer as quickly as possible. This helps ensure that every single row has enough pieces to grow into a group of at least three.
After all the pieces have been placed, the computer takes a final look at every row. If any row is too short to be considered a proper group, it simply notes that the goal was not reached. If every single row is long enough, the task is finished.
Code Quality
Complexity Analysis
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++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | ||||||||
| leetcode.ca | C++ | Java | Python | Go | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 347: Top K Frequent Elements
- problem 1296: Divide Array in Sets of K Consecutive Numbers
Solved On The Same Day
- problem 680: Valid Palindrome II
- problem 478: Generate Random Point in a Circle
- problem 497: Random Point in Non-overlapping Rectangles
- problem 519: Random Flip Matrix
- problem 581: Shortest Unsorted Continuous Subarray
- problem 738: Monotone Increasing Digits
- problem 743: Network Delay Time
- problem 769: Max Chunks To Make Sorted
- problem 985: Sum of Even Numbers After Queries
- problem 1048: Longest String Chain
- problem 1094: Car Pooling
- problem 1324: Print Words Vertically
- problem 1680: Concatenation of Consecutive Binary Numbers
- problem 1823: Find the Winner of the Circular Game
- problem 1860: Incremental Memory Leak
- problem 1922: Count Good Numbers
- problem 2487: Remove Nodes From Linked List
- problem 381: Insert Delete GetRandom O(1) - Duplicates allowed
- problem 517: Super Washing Machines
- problem 632: Smallest Range Covering Elements from K Lists
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