- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can split array into consecutive subsequences in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of sorted integers, arr, as the first and the only argument.
Our function should return true if and only if we can split the array into 1 or more subsequences such that each subsequence consists of consecutive integers and has length at least 3, false otherwise.
For example, if the input to the function is
Input
const arr = [1, 2, 3, 3, 4, 5];
Output
const output = true;
Output Explanation
We can split them into two consecutive subsequences −
1, 2, 3 3, 4, 5
Example
Following is the code −
const arr = [1, 2, 3, 3, 4, 5]; const canSplit = (arr = []) => { const count = arr.reduce((acc, num) => { acc[num] = (acc[num] || 0) + 1 return acc }, {}) const needed = {} for (const num of arr) { if (count[num] <= 0) { continue } count[num] -= 1 if (needed[num] > 0) { needed[num] -= 1 needed[num + 1] = (needed[num + 1] || 0) + 1 } else if (count[num + 1] > 0 && count[num + 2]) { count[num + 1] -= 1 count[num + 2] -= 1 needed[num + 3] = (needed[num + 3] || 0) + 1 } else { return false } } return true } console.log(canSplit(arr));
Output
true
- Related Articles
- Split Array into Consecutive Subsequences in C++
- Split number into n length array - JavaScript
- Split one-dimensional array into two-dimensional array JavaScript
- Can array form consecutive sequence - JavaScript
- Split Array of items into N Arrays in JavaScript
- Program to check whether we can split a string into descending consecutive values in Python
- Program to check whether we can split list into consecutive increasing sublists or not in Python
- Split string into groups - JavaScript
- Number Split into individual digits in JavaScript
- Split string into equal parts JavaScript
- Consecutive elements sum array in JavaScript
- Split number into 4 random numbers in JavaScript
- How to split a vector into smaller vectors of consecutive values in R?\n
- How can I split an array of Numbers to individual digits in JavaScript?
- How to split comma and semicolon separated string into a two-dimensional array in JavaScript ?

Advertisements