01 / 21

Sorting +
Scanning

Learn the powerful two-phase pattern: sort first, then scan linearly to solve problems in \( O(n \log n) \) time that would otherwise require \( O(n^2) \).

C++

What Is Sorting + Scanning?

A sorting + scanning pattern is a two-phase algorithmic strategy. First you sort the input data. Then you scan (iterate) through the sorted data in a single pass, exploiting the order to solve the problem efficiently.

This pattern appears constantly in competitive programming, technical interviews, and real-world systems: finding duplicates, detecting overlaps, computing closest pairs, and more.

The Two Phases

Phase 1: Sort
Use std::sort to arrange elements in non-decreasing order. Cost: \( O(n \log n) \).
Phase 2: Scan
Walk through the sorted array once, comparing adjacent or nearby elements. Cost: \( O(n) \).

Why Does Sorting Help?

Unsorted 5 2 8 2 9 Check every pair?
\( O(n^2) \) comparisons
std::sort Sorted 2 2 5 8 9 scan match! Duplicates are now
adjacent: \( O(n) \) scan

Sorting brings related elements next to each other. Instead of checking all \( \binom{n}{2} \) pairs, you only compare adjacent elements.

The Core Pattern in C++

// Phase 1: Sort sort(v.begin(), v.end()); // Phase 2: Scan for (int i = 1; i < (int)v.size(); i++) { if (v[i] == v[i-1]) { // found a duplicate pair } }

Complexity Guarantee

\( n \) (input size)
time
\( O(n^2) \)
\( O(n \log n) \)
\( O(n) \) scan only

Sort + Scan vs. Hash-Based

Sort + Scan Hash Set / Map
Time complexity \( O(n \log n) \) \( O(n) \) average
Extra memory \( O(1) \) extra (in-place sort) \( O(n) \)
Order preserved? No (array is reordered) Yes (original order intact)
Works with custom comparators? Yes, naturally Needs custom hash
Best for Interval problems, k-closest, ranges Simple lookups, counting

How to Apply the Pattern

1
Identify the relationship. Are you looking for duplicates, closest values, overlapping intervals, or ordered groupings?
2
Choose a sort key. Decide what to sort by: value, start time, x-coordinate, etc. Use a custom comparator if needed.
3
Sort with std::sort. Call sort(v.begin(), v.end()) or pass a lambda for custom ordering.
4
Scan once. Iterate with a single loop, comparing v[i] with v[i-1] or maintaining a running state variable.
5
Collect results. Track your answer (count, max, min) as you scan. Return it after the loop.

Example 1: Find Duplicates

Problem: Given an array of integers, determine if any value appears at least twice.

bool containsDuplicate(vector<int>& nums) { sort(nums.begin(), nums.end()); for (int i = 1; i < (int)nums.size(); i++) { if (nums[i] == nums[i-1]) return true; } return false; }

Example 2: Minimum Difference

Problem: Find the minimum absolute difference between any two elements in an array.

int minDiff(vector<int>& a) { sort(a.begin(), a.end()); int ans = INT_MAX; for (int i = 1; i < (int)a.size(); i++) ans = min(ans, a[i] - a[i-1]); return ans; }

Example 3: Merge Overlapping Intervals

Problem: Given a list of intervals \( [a_i, b_i] \), merge all overlapping intervals.

1 3 4 6 8 10 12 Unsorted intervals: [1,3] [6,10] [2,6] [8,12] sort by start Merged: [1, 12]

Sort by start time, then scan: if the current interval overlaps the previous, merge them by extending the end. Otherwise, start a new group.

Merge Intervals: Code

vector<pair<int,int>> merge( vector<pair<int,int>>& iv) { sort(iv.begin(), iv.end()); vector<pair<int,int>> res; for (auto& [a, b] : iv) { if (!res.empty() && a <= res.back().second) res.back().second = max(res.back().second, b); else res.push_back({a, b}); } return res; }

Scan Variations

Adjacent Compare
Compare v[i] with v[i-1]. Used for duplicates, min gap, longest streak.
Running State
Maintain a variable (e.g., current interval end) updated at each step. Used for merging intervals.
Two Pointers
Use two indices scanning from both ends or at different speeds. Used for pair-sum, 3-sum problems.

Custom Comparators

Sometimes the default sort order is not enough. Use a lambda to define your own sort key:

// Sort intervals by end time (greedy) sort(iv.begin(), iv.end(), [](const pair<int,int>& a, const pair<int,int>& b) { return a.second < b.second; }); // Sort strings by length, then lex sort(words.begin(), words.end(), [](const string& a, const string& b) { if (a.size() != b.size()) return a.size() < b.size(); return a < b; });

Common Mistakes

✕ Forgetting to Sort
Writing the scan loop but never calling sort() first. The adjacent-compare logic only works on sorted data.
✕ Off-by-One in Scan
Starting the loop at i = 0 and accessing v[i-1] causes an out-of-bounds read. Start at i = 1.
✕ Using <= in Comparator
std::sort requires strict weak ordering. Using <= instead of < leads to undefined behavior and crashes.

Summary of Sort + Scan Problems

Problem Sort Key Scan Type Complexity
Find duplicates Value Adjacent == \( O(n \log n) \)
Min difference Value Adjacent diff \( O(n \log n) \)
Merge intervals Start time Running end \( O(n \log n) \)
Two-sum (sorted) Value Two pointers \( O(n \log n) \)
Max non-overlapping End time Greedy pick \( O(n \log n) \)

Question 1 of 5

What is the total time complexity of a sort + scan algorithm on an array of \( n \) elements?

Question 2 of 5

When scanning a sorted array for duplicates, what should you compare at each step?

Question 3 of 5

To merge overlapping intervals, what should you sort by?

Question 4 of 5

What happens if you use <= instead of < in a custom comparator passed to std::sort?

Question 5 of 5

You need to find the two closest values in an unsorted array. Which approach is most efficient?