I've written the following program which splits an array into size subarrays using JS's slice function, I'm trying to figure out the time complexity for this algorithm:
function chunk(array, size) {
if(array.length < size)
return [array];
let result = [];
for(let i = 0; i < array.length; i += size)
result.push(array.slice(i, i+size));
return result;
}
My current understanding is that the complexity is O(n*size) because we iterate through the whole array size times. If someone could help me figure this solution it would be greatly appreciated! Thanks!
It's O(n)
.
You iterate through the array n/size
times, and each iteration is O(size)
because it makes a slice of size
elements. So the total amount of work is n/size * size
, which is n
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.