Split Array into Consecutive Subsequences

Medium · Arrays & Hashing · Array · Hash Table · Greedy · Heap (Priority Queue)

Problem

You are given an integer array nums sorted in non-decreasing order. Split it into one or more subsequences so that every element belongs to exactly one subsequence and each subsequence

Return true if such a split exists, and false otherwise.

Examples

Input: nums = [1,2,3,4,4,5,6]
Output: true

Split into [1,2,3,4] and [4,5,6].

Input: nums = [5,6,6,7,7,8]
Output: true

Split into [5,6,7] and [6,7,8].

Input: nums = [1,2,4,5,6]
Output: false

1 and 2 cannot grow to length 3 because 3 is missing.

Constraints

Approaches

Follow-up

If the minimum length were k instead of 3, the counting greedy would have to claim k numbers at once, O(n · k). The heap version handles any k by extending the shortest run; the use cases ask exactly that, and for the fewest runs when any length is allowed.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…