C++20 sections · 1024 units
Open in Course

Unique Pattern

Complete deduplication

I'll show you the standard pattern for removing all duplicates from a container. First, sort the elements: sort(v.begin(), v.end()) to group duplicates together. Then call unique and erase together: v.erase(unique(v.begin(), v.end()), v.end()).

This shrinks the vector to contain only the distinct elements in sorted order. The final vector is sorted with no duplicates remaining. Total time complexity is O(nlog⁡n)O(n \log n) dominated by the sorting step.

This pattern appears in many problems.