JavaScript implementation of ordered set depending on the efficient implementation of Array.prototype.splice()
.
The Set
object in JavaScript is an implementation of an unordered set that does not keep the order of its elements.
The API of this implementation is similar to the JavaScript Set object. It also keeps the set elements in a sorted array.
-
Efficiently implemented ordered sets and their variants are handy for some coding problems in programming contests for me. But, JavaScript does not provide such a data structure by default.
For example, theset
type in the standard C++ library preserves the ordering of elements of a set. So, getting the first or last element of a mutable set is easy and efficient. In detail, the set type takes$O(\log n)$ time to add or remove an element and to get the first or last element since it is implemented as a balanced binary search tree such as the Red-black tree. -
Modern JavaScript engines optimized Array operations well.
For example,Array.prototype.splice
would be fast enough for a small-size array though its time complexity would be$O(n)$ .
- C++: set, map, multiset
- Java: TreeSet, TreeMap
- Python (sortedcontainers): SortedSet, SortedDict, SortedList