01 / 20

Sorting as a
Solution Strategy

Learn to recognize when sorting data first transforms hard problems into simple ones: reducing complexity from \(O(n^2)\) to \(O(n \log n)\) and unlocking powerful algorithmic techniques.

C++

What Is Sorting?

Sorting means rearranging elements into a defined order: ascending, descending, alphabetical, or by any comparison rule. In C++, std::sort handles this in \(O(n \log n)\) average time.

Unsorted 7 2 9 1 sort() Sorted 1 2 7 9
Time: \(O(n \log n)\)
IntroSort (std::sort default)

Why Sort First?

Sorting creates structure in raw data. That structure lets you replace brute-force nested loops with elegant single-pass or binary-search techniques.

Binary Search
Find any element in \(O(\log n)\) instead of \(O(n)\) linear scan.
Two Pointers
Sweep from both ends to find pairs, merge ranges, or detect duplicates in \(O(n)\).
Greedy Algorithms
Process items in order of size, deadline, or priority to make locally optimal choices.

The Sorting Advantage Visually

Consider the problem: "Find if any two elements sum to a target." Without sorting, you check every pair. With sorting, two pointers solve it in one pass.

Brute Force: \(O(n^2)\)
for i in 0..n: for j in i+1..n: if a[i]+a[j]==T: ✓ Nested loops = slow Sort first!
Sort + Two Pointers: \(O(n \log n)\)
sort(a) lo=0, hi=n-1 move lo++ or hi-- each step Single pass = fast n = 100,000 10,000,000,000 operations n = 100,000 1,700,000 operations ~5,900x faster

The Core Principle

Problem Sort? Yes Sort Data
\(O(n \log n)\)
Simple Algo
\(O(n)\) or \(O(\log n)\)
No Other approach

Sorting in C++

// Include the algorithm header #include <algorithm> #include <vector> std::vector<int> v = {7, 2, 9, 1, 5}; // Ascending (default) std::sort(v.begin(), v.end()); // v = {1, 2, 5, 7, 9} // Descending std::sort(v.begin(), v.end(), std::greater<int>()); // v = {9, 7, 5, 2, 1}
Time
\(O(n \log n)\) average and worst case (IntroSort)
Space
\(O(\log n)\) stack space for recursion

Sorted vs Unsorted Approaches

Problem Without Sorting With Sorting
Find duplicates \(O(n^2)\) nested loops \(O(n \log n)\) sort + linear scan
Two-sum target \(O(n^2)\) check all pairs \(O(n \log n)\) sort + two pointers
Find median \(O(n^2)\) naive selection \(O(n \log n)\) sort + index \(n/2\)
Closest pair \(O(n^2)\) all distances \(O(n \log n)\) sort + neighbors
Count inversions \(O(n^2)\) nested comparison \(O(n \log n)\) merge sort variant

How to Apply the Strategy

1
Read the problem. Identify what you are searching for, comparing, or grouping.
2
Ask the key question: "Would sorted order make adjacency, proximity, or lookup easier?"
3
Check the constraint: Is the input small enough that \(O(n \log n)\) fits in time? (Almost always yes.)
4
Sort, then solve. Apply binary search, two pointers, or a greedy sweep on the sorted data.
5
Verify: Does sorting preserve the information you need? (If you need original indices, store them before sorting.)

Example 1: Finding Duplicates

Problem: Given an array of integers, determine if any value appears more than once.

After sorting: duplicates become neighbors 1 3 5 5 7 8 8 9 Duplicate! Duplicate!
Just compare \(v[i] == v[i+1]\) in one pass: \(O(n)\)
std::sort(v.begin(), v.end()); for (int i = 0; i < v.size() - 1; i++) { if (v[i] == v[i + 1]) return true; // found duplicate }

Example 2: Two-Sum with Two Pointers

Problem: Given a sorted array and a target \(T\), find two elements that sum to \(T\).

1 3 5 7 9 11 15 lo hi
Target \(T = 16\)
\(sum = 1 + 15 = 16 = T\) ✓ Found!
If \(sum < T\): move lo right. If \(sum > T\): move hi left.

Example 3: Greedy Scheduling

Problem: Given \(n\) tasks with deadlines and durations, maximize tasks completed on time. Sort by deadline, then greedily pick tasks.

0 2 4 6 8 Tasks sorted by deadline Task A (d=3) Task B (d=5) Task C (d=7) All 3 tasks fit before their deadlines ✓

When Not to Sort

Sorting is powerful but not universal. There are situations where it destroys the information you need or is overkill.

Order Matters
If the problem depends on original positions (e.g., "longest increasing subsequence"), sorting destroys that structure.
Hash Map Exists
Two-sum can also be solved in \(O(n)\) with a hash map. If you only need lookup, hashing may be faster.
Already Linear
Finding min/max is already \(O(n)\). Sorting to find the first element wastes time: \(O(n \log n) > O(n)\).

Patterns Unlocked by Sorting

1
Binary Search: After sorting, find any element in \(O(\log n)\) using std::lower_bound.
2
Two Pointers: Use a left and right pointer converging inward for pair/sum problems.
3
Sliding Window: Process sorted intervals or ranges by moving a window over contiguous elements.
4
Greedy Selection: Sort by weight, value, or deadline and pick items in that order.
5
Duplicate Detection: Adjacent equal elements in sorted order make duplicates trivial to find.

Common Mistakes

✕ Sorting When Order Matters
You need original indices but sort the array, losing positional information. Store index pairs first.
✕ Sorting to Find Min/Max
Finding the minimum is \(O(n)\). Sorting for it wastes \(O(n \log n)\) for no benefit.
✕ Forgetting Stability
std::sort is not stable. If you need equal elements to keep their original order, use std::stable_sort.
✕ Sorting Inside a Loop
Accidentally sorting inside a repeated operation turns \(O(n \log n)\) into \(O(n^2 \log n)\). Sort once, outside the loop.

Summary Table

Signal Technique After Sort Total Complexity
"Find if X exists" Binary search \(O(n \log n)\)
"Find a pair summing to T" Two pointers \(O(n \log n)\)
"Find duplicates" Adjacent comparison \(O(n \log n)\)
"Schedule tasks optimally" Greedy sweep \(O(n \log n)\)
"Find k-th smallest" Direct index access \(O(n \log n)\)
"Merge overlapping intervals" Linear merge \(O(n \log n)\)

Question 1 of 5

You need to check whether an array of \(n\) integers contains any duplicate values. Which approach is most efficient?

Question 2 of 5

After sorting an array, which algorithmic technique lets you find two elements that sum to a target in \(O(n)\) time?

Question 3 of 5

Why is it wasteful to sort an array just to find its minimum element?

Question 4 of 5

You have a list of meeting intervals [(1,3), (5,8), (2,6), (9,10)]. To merge overlapping intervals efficiently, what should you do first?

Question 5 of 5

A problem asks you to find the longest increasing subsequence (LIS) of an array. Should you sort the array first?