In: Computer Science
//Trying to get this code with JavaScript. I could partition the subarrays, but I don't know how to check for unique elements
Given an array of integers check if it is possible to partition the array into some number of subsequences of length k each, such that:
If it is possible to partition the array into subsequences while satisfying the above conditions, return “Yes”, else return “No”. A subsequence is formed by removing 0 or more elements from the array without changing the order of the elements that remain. For example, the subsequence of [1,2,3] are [], [1], [2], [3], [1,2], [2,3], [1,3], [1, 2, 3].
Example
k = 2
numbers = [1, 2, 3, 4]
The array can be portioned with elements [1, 2] as the first subsequence, and elements [3, 4] as the next subsequence. Therefore, return “Yes”.
Example 2
k = 3
numbers = [1, 2, 2, 3]
There is no way to partition the array into subsequences such that all subsequences are of length 3 and each element in the array occurs in exactly one subsequence. Therefore return “No”.
Function Description
Complete the function partitionArray in the editor below. The function has to return one string denoting the answer.
partitionArray has the following parameters:
int k: an integer
int numbers[n]: an array of integers
function partitionArray(k, numbers) {
//Write your code here
}
Working code implemented in JavaScript and appropriate comments provided for better understanding.
Source Code:
// Array Partitioning
// Given Array
// check if possible to partion into subsequences of
// length k each
// each element in array occurs exactly 1 subsequence
// all numbers in subsequence are distinct
// elements in the array having same value must be
// in different subsequences
// if possible to partition array satisfying all conditions
above
// return 'yes', else return 'no'
// ex:
// n = 4 numbers in array
// length of each subsequence needs to be
// k = 2
// arr = [1,2,3,4]
// one possible way
// choose first 2 elements of array ==> [1,2] as first
subsequence
// next 2 elements of array => [3,4] next subsequence
// so output === 'yes'
// ex2:
// n = 4
// k = 3
// arr = [1,2,2,3]
// no way to partition array where each subsequence is length of
3
// and each element in array occurs only once
// so output === 'no'
function partitionArray(k, numbers) {
console.log('k:', k)
console.log('numbers', numbers)
const arrLen = numbers.length
console.log('arrLen', arrLen)
var arr1 = []
var arr2 = []
// if arr can by evenly divided k times proceed
if (arrLen % k === 0) {
console.log('yes')
return 'Yes'
} else {
// else return 'no'
console.log('no')
return 'No'
}
}
// Input:
// 2 - number of partitions
// 4 - length of array
// 3 - array[0]
// 5 - array[1]
// 3 - array[2]
// 2 - array[3]
// k = 2
// numbers = [ 3, 5, 3, 2 ]
partitionArray(2, [1, 2, 3, 4]) // output 'Yes'
partitionArray(3, [1, 2, 2, 3]) // output 'No'
Sample Output Screenshots: