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