01 / 20

Sorting +
Scanning

Master the powerful two-step pattern: sort your data, then scan through it to solve problems that would otherwise require brute force.

Python

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.

Phase 1: Sort
Arrange elements by value, key, or custom criteria using Python's built-in sort.
Phase 2: Scan
Walk through sorted data once, using simple comparisons to find the 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.

Unsorted 8 3 1 5 sorted() Sorted 1 3 5 8 Scan left → right Brute Force
\( O(n^2) \)
Sort + Scan
\( O(n \log n) \)

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.

Without Sorting
Compare every pair: \( \binom{n}{2} \) checks. Slow and tedious.
With Sorting
Sort once, then check each consecutive pair: only \( n - 1 \) checks.

The Pattern Formally

1
Sort the input list using sorted() or .sort(): costs \( O(n \log n) \).
2
Scan through the sorted list with a for loop, comparing adjacent (or nearby) elements: costs \( O(n) \).
3
Total time complexity: \( O(n \log n) + O(n) = O(n \log n) \).

Python's Sorting Tools

sorted(lst)
Returns a new sorted list. The original is unchanged. Works on any iterable.
lst.sort()
Sorts in place, returns None. Slightly faster (no copy), but mutates the list.
# sorted() returns a new list nums = [8, 3, 1, 5] ordered = sorted(nums) # [1, 3, 5, 8] # .sort() modifies in place nums.sort() # nums is now [1, 3, 5, 8] # Custom key: sort by absolute value vals = [-4, 2, -1, 7] sorted(vals, key=abs) # [-1, 2, -4, 7]

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

1
Identify the goal: Are you looking for closest pairs, duplicates, a running max/min, or grouping adjacent elements?
2
Choose a sort key: Sort by the natural value, by a tuple (priority, value), or by a custom function.
3
Sort the data: Call sorted() or .sort() once.
4
Scan with a loop: Iterate with a for loop, tracking state (e.g., previous value, running count, best result).
5
Return the answer: After one pass, you have your result.

Example 1: Closest Pair

Given a list of integers, find the minimum absolute difference between any two elements.

def min_diff(nums): nums.sort() best = float('inf') for i in range(1, len(nums)): diff = nums[i] - nums[i - 1] best = min(best, diff) return best

Walkthrough: Closest Pair

Input: [10, 3, 7, 1, 15] After sort: [1, 3, 7, 10, 15] 1 3 7 10 15 diff=2 diff=4 diff=3 diff=5 Minimum difference = 2 (between 1 and 3)

Example 2: Contains Duplicate

Given a list, determine if any value appears at least twice.

def contains_duplicate(nums): nums.sort() for i in range(1, len(nums)): if nums[i] == nums[i - 1]: return True return False

Example 3: Largest Gap

Given a list of numbers, find the largest difference between consecutive elements when sorted.

def largest_gap(nums): nums.sort() max_gap = 0 for i in range(1, len(nums)): gap = nums[i] - nums[i - 1] max_gap = max(max_gap, gap) return max_gap

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.

# Sort strings by length words = ["banana", "fig", "apple", "kiwi"] sorted(words, key=len) # ['fig', 'kiwi', 'apple', 'banana'] # Sort tuples by second element pairs = [(1, 5), (3, 2), (2, 8)] sorted(pairs, key=lambda x: x[1]) # [(3, 2), (1, 5), (2, 8)]

Common Scanning Patterns

Adjacent Compare
Compare nums[i] with nums[i-1]: duplicates, gaps, closest pairs.
Running Tracker
Track a running variable (max, min, count) as you iterate through sorted data.
Two Pointers
Use left and right pointers on sorted data: pair sums, partitioning.

Common Mistakes

✕ Using .sort() Return
lst.sort() returns None. Writing x = lst.sort() gives you None, not a sorted list.
✕ Off-By-One in Scan
Starting the loop at i = 0 and accessing nums[i-1] wraps to the last element in Python.
✕ Forgetting to Sort
Scanning unsorted data only checks if consecutive elements match, missing non-adjacent duplicates.

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

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

What happens when you call mystery([3, 1, 2])?