AlgoMaster Logo

Split Array into Consecutive Subsequences

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Greedy with Frequency and Append Maps

Intuition:

The task is to determine if we can split a given array into consecutive subsequences of length at least 3. The approach involves using two hash maps:

  1. frequency map to keep track of the remaining occurrences of each element.
  2. appendNeeded map to track the need to append an element to a previously formed subsequence.

The basic greedy strategy is:

  • We iterate through the array and for each element num:
    • First, check if num can be added to an existing subsequence where it can help form a valid consecutive sequence.
    • If num can't be added to any existing subsequence, try to start a new subsequence from it.
    • If neither is possible, we should return false because it is impossible to form the desired subsequences.

Steps:

  1. Use a frequency map to track the available counts of each number.
  2. Use an appendNeeded map to track if a number needs to be the next element in a subsequence.
  3. Loop through each number num in the input:
    • If the frequency of num is zero, continue, meaning it's already used.
    • If num can be appended to a subsequence (i.e., appendNeeded[num] > 0), reduce the need and increase the need for the next number.
    • If num can't be appended, try starting a new subsequence num, num+1, num+2 and update the necessary maps.
    • If neither appending to a subsequence nor starting one is possible, return false.
  4. If we can iterate through without issue, return true.

Code: