Sorting +
Scanning
Master the powerful two-step pattern: sort your data, then scan through it to solve problems that would otherwise require brute force.
What Is Sorting + Scanning?
Sorting + Scanning is a two-phase algorithmic pattern used to solve problems efficiently. First, you sort the data into a meaningful order. Then, you scan (iterate) through the sorted data in a single pass to extract your answer.
Why Sort First?
Many problems require comparing every pair of elements, leading to \( O(n^2) \) brute-force solutions. Sorting first (at \( O(n \log n) \) cost) lets you solve them with a single \( O(n) \) scan.
A Real-World Analogy
Imagine finding the two closest numbers in a pile of index cards. Without sorting, you would compare every card to every other card. But if you sort them first, the closest pair must be neighbors: just scan once.
The Pattern Formally
Python's Sorting Tools
sorted() vs .sort()
| sorted(lst) | lst.sort() | |
|---|---|---|
| Returns | New sorted list | None |
| Mutates original? | No | Yes |
| Works on | Any iterable | Lists only |
| Memory | \( O(n) \) extra | \( O(1) \) extra |
| Supports key=? | Yes | Yes |
How to Apply the Pattern
Example 1: Closest Pair
Given a list of integers, find the minimum absolute difference between any two elements.
Walkthrough: Closest Pair
Example 2: Contains Duplicate
Given a list, determine if any value appears at least twice.
Example 3: Largest Gap
Given a list of numbers, find the largest difference between consecutive elements when sorted.
Sorting with Custom Keys
Sometimes you need to sort by something other than natural order. The key parameter lets you define a custom sorting criterion.
Common Scanning Patterns
Common Mistakes
Pattern Summary
| Problem Type | Sort By | Scan For | Time |
|---|---|---|---|
| Closest pair | Value | Min adjacent diff | \( O(n \log n) \) |
| Has duplicates | Value | Adjacent equality | \( O(n \log n) \) |
| Largest gap | Value | Max adjacent diff | \( O(n \log n) \) |
| Kth smallest | Value | Index k-1 | \( O(n \log n) \) |
| Merge intervals | Start time | Overlapping neighbors | \( O(n \log n) \) |
Question 1 of 5
What is the overall time complexity of the sort + scan pattern on a list of \( n \) elements?
Question 2 of 5
What does lst.sort() return in Python?
Question 3 of 5
Consider this code:
def find_dup(nums):
nums.sort()
for i in range(1, len(nums)):
if nums[i] == nums[i - 1]:
return nums[i]
return None
What does this function return for the input [5, 2, 3, 5, 1]?
Question 4 of 5
Why does sorting help when finding the minimum difference between any two elements in a list?
Question 5 of 5
Consider this code:
def mystery(nums):
result = nums.sort()
for i in range(1, len(result)):
if result[i] == result[i - 1]:
return True
return False
What happens when you call mystery([3, 1, 2])?