Split Array into Consecutive Subsequences in C++


Suppose we have an array nums that is sorted in ascending order. We have to return true if and only if we can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and whose length at least 3. So if the input is like [1,2,3,3,4,4,5,5], then the output will be True, as we have two consecutive sequences. These are [1,2,3,4,5] and [3,4,5].

To solve this, we will follow these steps −

  • Make a map m and store the frequency of nums into m, store size of nums into m
  • cnt := n
  • for i in range 0 to n – 1
    • x := nums[i]
    • if m[x] and m[x + 1] and m[x + 2]
    • decrease m[x], m[x + 1] and m[x + 2] by 1, increase x by 3 and decrease count by 3
    • while m[x] > 0 and m[x] > m[x – 1]
      • decrease cnt by 1, decrease m[x] by 1 and increase x by 1
  • return true if cnt is 0, otherwise false
  • Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool isPossible(vector<int>& nums) {
      unordered_map <int, int> m;
      int n = nums.size();
      for(int i = 0; i < n; i++){
         m[nums[i]]++;
      }
      int cnt = n;
      for(int i = 0; i < n; i++){
         int x = nums[i];
         if(m[x] && m[x + 1] && m[x + 2]){
            m[x]--;
            m[x + 1]--;
            m[x + 2]--;
            x += 3;
            cnt -= 3;
            while(m[x] > 0 && m[x] > m[x - 1]){
               cnt--;
               m[x]--;
               x++;
            }
         }
      }
      return cnt == 0;
   }
};
main(){
   vector<int> v = {1,2,3,3,4,4,5,5};
   Solution ob;
   cout << (ob.isPossible(v));
}

Input

[1,2,3,3,4,4,5,5]

Output

1

Updated on: 04-May-2020

362 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements