Problem 659

Abstract / Summary

Check if a sorted array can be divided into groups where each group is a set of consecutive increasing numbers.

Note

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

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
21 lines | 594 bytes | submitted September 23, 2023 | GitHub   18% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Hash Table
  • Heap (Priority Queue)
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.77 | σ = 1.74

Complexity Analysis

not analyzed yet

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++ 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++
33 links | 22 authors | 9 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

21 solutions   September 23, 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