01 / 20

Sorting +
Scanning

Master the powerful two-phase pattern: sort first, then scan linearly to solve array problems efficiently in Java.

Java

What Is Sort + Scan?

Sort + Scan is a two-phase algorithmic pattern where you first sort an array to impose order, then make a single linear pass (scan) to extract the answer. By sorting first, relationships between elements become obvious: duplicates sit side by side, gaps become visible, and extremes move to the edges.

Why Sort First?

Duplicates cluster
Equal values become adjacent, so one pass detects repeats.
Gaps appear
Missing numbers reveal themselves as jumps between neighbors.
Extremes at edges
Min and max are at index \(0\) and \(n-1\): instant access.

The Two Phases Visualized

Phase 1: Sort Unsorted 5 2 8 2 9 ↓ Arrays.sort() Sorted 2 2 5 8 9 Phase 2: Scan Compare neighbors 2 2 5 8 9 Equal! Duplicate found: 2
Total: \(O(n \log n) + O(n) = O(n \log n)\)

The Pattern Template

// Sort + Scan template Arrays.sort(arr); // Phase 1 for (int i = 1; i < arr.length; i++) { // Phase 2 if (condition(arr[i], arr[i-1])) { // found answer } }

Sort + Scan vs Brute Force

Brute Force Sort + Scan
Approach Nested loops: check every pair Sort, then single pass
Time \(O(n^2)\) \(O(n \log n)\)
Space \(O(1)\) \(O(1)\) to \(O(n)\)
Code complexity Simple but slow Simple and fast
When \(n = 10{,}000\) 100,000,000 ops ~133,000 ops

Sort + Scan vs HashMap

Sort + Scan
Time: \(O(n \log n)\)
Space: \(O(\log n)\) to \(O(n)\)
Mutates the original array
Best when: space matters, or you need ordered relationships (gaps, ranges, closest pair)
HashMap
Time: \(O(n)\)
Space: \(O(n)\) extra
Preserves original order
Best when: you need \(O(n)\) time or must keep original indices

How to Apply the Pattern

1
Recognize the signal: the problem asks about duplicates, gaps, closest values, or pairwise relationships in an array.
2
Sort the array using Arrays.sort(arr). This is your Phase 1.
3
Design the scan condition: what relationship between arr[i] and arr[i-1] answers the question?
4
Write the loop from index \(1\) to \(n-1\), checking your condition each step.
5
Return the result. Handle edge cases: empty array, single element, all elements equal.

Example 1: Find Duplicates

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

public static boolean containsDuplicate(int[] nums) { Arrays.sort(nums); // Phase 1: sort for (int i = 1; i < nums.length; i++) { // Phase 2: scan if (nums[i] == nums[i - 1]) { return true; // adjacent equal = duplicate } } return false; }

Tracing containsDuplicate

Input: [3, 1, 4, 1, 5] After Arrays.sort(): 1 [0] 1 [1] 3 [2] 4 [3] 5 [4] Scan: i=1: arr[1]=1 == arr[0]=1? YES ✓ return true (duplicate found)

Example 2: Minimum Gap

Problem: Find the smallest absolute difference between any two elements in an array of at least 2 elements.

public static int minGap(int[] arr) { Arrays.sort(arr); // Phase 1 int min = Integer.MAX_VALUE; for (int i = 1; i < arr.length; i++) { // Phase 2 int gap = arr[i] - arr[i - 1]; if (gap < min) { min = gap; } } return min; }

Tracing minGap

Input: [10, 3, 7, 1, 15] → Sorted: [1, 3, 7, 10, 15] 1 3 7 10 15 2 4 3 5 i arr[i]-arr[i-1] min so far 1 3 - 1 = 2 2 2 7 - 3 = 4 2 3 10 - 7 = 3 2 4 15 - 10 = 5 2 return 2

Example 3: Count Unique Values

Problem: Count the number of distinct values in an array.

public static int countUnique(int[] arr) { if (arr.length == 0) return 0; Arrays.sort(arr); // Phase 1 int count = 1; // first element is always unique for (int i = 1; i < arr.length; i++) { // Phase 2 if (arr[i] != arr[i - 1]) { count++; // new value found } } return count; }

Common Mistakes

✕ Off-by-One Start
Starting the scan at \(i=0\) and accessing arr[i-1] causes an ArrayIndexOutOfBoundsException. Always start at \(i=1\).
✕ Forgetting to Sort
Running the scan on an unsorted array means neighbors aren't meaningful. The scan will miss duplicates and produce wrong gaps.
✕ Ignoring Mutation
Arrays.sort() modifies the original array. If the caller needs the original order, clone first: arr.clone().

Pattern Summary

Problem Type Scan Condition Returns
Has duplicates? \(\texttt{arr[i] == arr[i-1]}\) boolean
Count unique \(\texttt{arr[i] != arr[i-1]}\) int count
Min gap \(\texttt{arr[i] - arr[i-1] < min}\) int min
Find missing \(\texttt{arr[i] - arr[i-1] > 1}\) int missing
Longest run \(\texttt{arr[i] == arr[i-1] + 1}\) int length

Question 1 of 5

What is the total time complexity of the Sort + Scan pattern?

Question 2 of 5

In the scan phase, why does the loop typically start at \(i = 1\) rather than \(i = 0\)?

Question 3 of 5

What is the value of count after this code runs?

Question 4 of 5

Which problem is NOT a good fit for the Sort + Scan pattern?

Question 5 of 5

A key disadvantage of Sort + Scan compared to using a HashMap is: