Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Pavel Kostenko
Space complexity of unique set is not quite O(n)

Pavel Kostenko

Dec 27, 2024

In the solution

Space Complexity:

  1. Count Map: We use a hashmap (or dictionary) to store the count of occurrences of each number. In the worst case, if all numbers in the array are unique, the size of the count map is (n). So, the space complexity for the count map is (O(n)).
  2. Unique Counts Set: We use a hashset to store unique counts. In the worst case, if all numbers in the array have a unique count (which is highly unlikely and would mean that each number repeats a unique number of times), the size of the set is (n). So, the space complexity for the unique counts set is (O(n)).

Combining the two data structures, the overall space complexity is (O(n) + O(n) = O(n)).

We can do better

Space complextity for Unique Counts Set does not grows linearly, it grows sub linearly

let's take a set with 10 numbers all having unique occurrences:

1 2 3 4 5 6 7 8 9 10 // n - is length of array we need to form to have a unique set of given size n uniqSet Size 1 1 3 2 6 3 // array will have 6 elements, but only 3 can be unique (ideal case, same for every row) 10 4 15 5 21 6 28 7 36 8 45 9 55 10

By observing this pattern we can (ChatGPT can) asses that n grows similar to triangular numbers

which is n = (k(k+1)) / 2 => sqrt(2n). where k is the uniqSet size

the groth pattern is therefore can be simplified as sqrt(n) which is sub linear.

However the Count Map O(n) space complexity dominates, and therefore the final space complexity is O(n).

0

0

Comments
Comments

On this page