0

We can find unique elements of array using JavaScript Set(). You can create a set by either giving array initially or use Set.prototype.add(). What are time complexities and space complexities for each case?

With constructor

const mySet = new Set(nElementsArray);

With add() method

const mySet = new Set();
for (const item of nElementsArray) {
  mySet.add(item);
}

For each of above what will be space and time complexity?

Salitha
  • 1,022
  • 1
  • 12
  • 32
  • 1
    The implementation details for how Set methods are implemented are not part of the language specification. One would *hope* that set operations would be something close to constant-time, but nothing forces an implementation to do that. – Pointy Jul 13 '23 at 17:34
  • Seems like you should write perf tests and figure out what is better for your use case. – epascarello Jul 13 '23 at 17:39
  • @RobertHarvey this has partial answer i guess, what i concerned is, whether providing entire array to the constructor is efficient than adding one by one. This question you mentioned is more about accessing existing elements and it compares with other forms of data structures – Salitha Jul 13 '23 at 18:05
  • 1
    `add` has `O(1)` average complexity. Both approaches you've shown are iterating over `nElementsArray`, which has linear time complexity (on the number of elemenets in the array), so it can't get better than `O(n)`. While the complexity of the `Set` constructor is not specified, it is very unlikely that it is worse. – Bergi Jul 13 '23 at 18:43

0 Answers0