Ordered sets & sorted containers

RoadmapsDSA

Overview

Data structures that maintain elements in sorted order while allowing fast (O(log n)) insertions, deletions, and lookups.

Standard arrays are O(n) to insert into. Hash sets are O(1) to insert but lose ordering. Sorted containers provide the best of both worlds for dynamic data that must remain ordered.

Where used: Leaderboards, Interval sweeping algorithms, Finding the closest value to a target dynamically

Why learn this

Common mistakes

Recall questions

Understanding checks

You are receiving a stream of integers. At any point, you need to find the element currently in the stream that is strictly greater than `X`. Should you use a Max Heap, a Hash Set, or a Sorted Set?

A Sorted Set.

A Hash Set has no order. A Max Heap only gives you the absolute maximum, not the 'next largest after X'. A Sorted Set allows logarithmic search (e.g., `upper_bound`) for arbitrary targets.

If you use `bisect.insort` to maintain a sorted list in Python, what is the time complexity of adding a new element?

O(N).

While `bisect` finds the insertion point in O(log N) time via binary search, actually inserting the element into a contiguous array requires shifting all subsequent elements, which is O(N).

Practice tasks

My Calendar I

Design a calendar system that allows you to add new events (start, end) only if they do not double-book an existing event. (Conceptualize how a Sorted Set of intervals solves this).

Continue learning

Previous: Hash Sets vs Maps

Previous: Binary Search

Return to DSA Roadmap