Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to check whether list can be split into sublists of k increasing elements in C++
Suppose we have a list of numbers called nums, and another number k, we have to check whether the list can be split into lists where each list contains k values and the values are consecutively increasing.
So, if the input is like nums = [4, 3, 2, 4, 5, 6], k = 3, then the output will be True, as we can split the list into [2, 3, 4] and [4, 5, 6]
To solve this, we will follow these steps −
Define one map
-
for each key it in m
increase m[it] by 1
ok := true
-
while (size of m is not 0 and ok is true), do −
ok := false
-
for each key-value pair it in m
-
if (it.key - 1) is not in m, then −
flag := true
-
for initialize i := it.key, when i <= it.key + k - 1, update (increase i by 1), do −
-
if i is not present in m, then −
flag := false
-
-
if flag is true, then −
-
for initialize i := it.key , when i <= it.key + k - 1, update (increase i by 1), do −
(decrease m[i] by 1)
-
if m[i] is same as 0, then −
delete i from m
ok := true
Come out from the loop
-
-
return true when m is empty, otherwise false.
Let us see the following implementation to get better understanding −
Example
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
bool solve(vector<int> nums, int k) {
map <int, int> m;
for(auto& it : nums){
m[it]++;
}
bool ok = true;
while(m.size() && ok){
ok = false;
for(auto& it : m){
if(!m.count(it.first - 1)){
bool flag = true;
for(int i = it.first; i <= it.first + k - 1;i++){
if(!m.count(i))
flag = false;
}
if(flag){
for(int i = it.first; i <= it.first + k - 1;i++){
m[i]--;
if(m[i] == 0)
m.erase(i);
}
ok = true;
break;
}
}
}
}
return m.empty();
}
};
main(){
vector<int> v = {4, 3, 2, 4, 5, 6};
Solution ob;
cout << ob.solve(v, 3);
}
Input
{4, 3, 2, 4, 5, 6}
Output
1