- Related Questions & Answers
- Program to check whether list can be split into sublists of k increasing elements in C++
- Program to check whether we can take all courses or not in Python
- Program to check whether we can unlock all rooms or not in python
- Program to check whether list is strictly increasing or strictly decreasing in Python
- Program to check whether we can get N queens solution or not in Python
- Program to split lists into strictly increasing sublists of size greater than k in Python
- Python program to check whether a list is empty or not?
- Program to check whether we can make k palindromes from given string characters or not in Python?
- Program to check whether given list is in valid state or not in Python
- C# program to check whether a list is empty or not
- Program to check we can reach leftmost or rightmost position or not in Python
- Program to check a string can be broken into given list of words or not in python
- Program to check whether we can make group of two partitions with equal sum or not in Python?
- Program to check whether parentheses are balanced or not in Python
- Can split array into consecutive subsequences in JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a list of numbers called nums and that is sorted in non-decreasing order, we have to check whether it can be split into any number of subsequences such that each subsequence has at minimum length of 3 and that is consecutively increasing.

So, if the input is like nums = [2, 3, 4, 4, 5, 6, 7], then the output will be True, as we can split the list to [2, 3, 4] and [4, 5, 6, 7].

To solve this, we will follow these steps −

- counts := A map that contains elements of nums and its counts
- starts := a new list
- ends := a new list
- for each x in the items of the count in sorted order, do
- if count[x] > count[x - 1], then
- l := list of size (count[x] - count[x - 1]) and fill with x
- insert l into starts

- if count[x] > count[x + 1], then
- l := list of size (count[x] - count[x + 1]) and fill with x
- insert l into starts

- if count[x] > count[x - 1], then
- return true when all (start, end) pair satisfies (start + 2 <= end), otherwise return false

Let us see the following implementation to get better understanding −

from collections import Counter class Solution: def solve(self, nums): count = Counter(nums) starts = [] ends = [] for x in sorted(count): if count[x] > count[x - 1]: starts.extend([x] * (count[x] - count[x - 1])) if count[x] > count[x + 1]: ends.extend([x] * (count[x] - count[x + 1])) return all(s + 2 <= e for s, e in zip(starts, ends)) ob = Solution() nums = [2, 3, 4, 4, 5, 6, 7] print(ob.solve(nums))

[6, 7, 5, 10, 13], 2

True

Advertisements