Time complexity of Array.from

淺唱寂寞╮ 提交于 2021-01-03 09:59:52

问题


What would be the time complexity of Array.from(). For example:

const set = new Set();
set.add('car');
set.add('cat');
set.add('dog');

console.log(Array.from(set)); // time complexity of making this convertion from Set to Array

回答1:


It's O(n). When used on an iterable (like a Set), Array.from iterates over the iterable and puts every item returned into the new array, so there's an operation for every item returned by the iterable.




回答2:


It is always going to be O(n) as the number of iterations would be directly proportional to the number of elements in the set. Actual Time complexity would be O(n) for retrieving values from a set O(n) for pushing into an array.

O(n) + O(n) = O(2n)

But since we do not consider a constant value when calculating using n value it should be O(n).



来源:https://stackoverflow.com/questions/59172980/time-complexity-of-array-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!