Skip to lesson

Problems solved by sorting first

Sorting transforms unstructured datasets, turning expensive nested searches into simple linear scans.

Sorting as an Algorithmic Transformation

Sorting by start time puts overlapping meetings next to each other. The first program checks every pair of meetings; the second sorts once and checks neighbours.

Example 1 · Brute force: compare every pair of meetings (O(n²) time, O(1) space)

MeetingRoomsBrute.javaJava
public class MeetingRoomsBrute {    public static boolean canAttendAllMeetings(int[][] meetings) {        for (int i = 0; i < meetings.length; i++) {            for (int j = i + 1; j < meetings.length; j++) {                boolean overlap = meetings[i][0] < meetings[j][1] && meetings[j][0] < meetings[i][1];                if (overlap) {                    return false;                }            }        }        return true;    }
    public static void main(String[] args) {        int[][] meetings1 = {{0, 30}, {5, 10}, {15, 20}};        int[][] meetings2 = {{7, 10}, {2, 4}};        System.out.println("Can attend 1: " + canAttendAllMeetings(meetings1));        System.out.println("Can attend 2: " + canAttendAllMeetings(meetings2));    }}
Output
Can attend 1: false
Can attend 2: true

What this code does

  • Two meetings overlap when each one starts before the other ends.
  • The two loops test every pair, so 50,000 meetings need about 1.25 billion checks.
  • It needs no sorting and no extra memory, but it is far too slow for big schedules.

Example 2 · Optimal: sort by start time, check neighbours (O(n log n) time, O(1) extra space)

MeetingRoomsDemo.javaJava
import java.util.Arrays;
public class MeetingRoomsDemo {    public static boolean canAttendAllMeetings(int[][] intervals) {        if (intervals.length <= 1) return true;        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
        for (int i = 1; i < intervals.length; i++) {            if (intervals[i][0] < intervals[i - 1][1]) {                return false; // Overlap found            }        }        return true;    }
    public static void main(String[] args) {        int[][] meetings1 = {{0, 30}, {5, 10}, {15, 20}};        int[][] meetings2 = {{7, 10}, {2, 4}};        System.out.println("Can attend 1: " + canAttendAllMeetings(meetings1));        System.out.println("Can attend 2: " + canAttendAllMeetings(meetings2));    }}
Output
Can attend 1: false
Can attend 2: true

What this code does

  • After sorting, a meeting can only overlap the one before it, so n - 1 neighbour checks replace n × (n - 1) / 2 pair checks.
  • Sorts intervals in ascending order of meeting start times.
  • Compares each meeting's start time with the previous meeting's end time.
  • Detects overlap when start time is strictly less than previous end time.

Without structure, checking all pairs requires quadratic O(n²) comparisons. Sorting the collection organizes the data along a single consistent dimension. Once ordered, related elements sit next to each other as immediate neighbors. Consider finding whether any two intervals overlap in a schedule. Brute force compares each interval with all other n - 1 intervals. For 50,000 meetings, checking all pairs requires 1.25 billion comparisons. Sorting intervals by start time solves the problem in a single linear pass. Trace interval overlap on [[1, 4], [7, 9], [2, 5]]: First sort by start time: [[1, 4], [2, 5], [7, 9]]. Inspect adjacent pairs: [1, 4] and [2, 5]. Since start time 2 is less than previous end time 4, an overlap is immediately detected. Only adjacent pairs need comparison once sorted, taking O(n log n) total time.

Merging Overlapping Intervals

Sort the intervals by start time, then walk through them once, extending the current interval while the next one overlaps. The examples go from repeated pair merging to one sorted pass.

Example 3 · Brute force: keep merging any overlapping pair until none is left (O(n³) time, O(n) space)

MergeIntervalsBrute.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class MergeIntervalsBrute {    public static int[][] merge(int[][] intervals) {        List<int[]> list = new ArrayList<>();        for (int[] iv : intervals) list.add(new int[] {iv[0], iv[1]});        boolean changed = true;        while (changed) {            changed = false;            for (int i = 0; i < list.size() && !changed; i++) {                for (int j = i + 1; j < list.size() && !changed; j++) {                    int[] a = list.get(i), b = list.get(j);                    if (a[0] <= b[1] && b[0] <= a[1]) {                        a[0] = Math.min(a[0], b[0]);                        a[1] = Math.max(a[1], b[1]);                        list.remove(j);                        changed = true;                    }                }            }        }        list.sort((a, b) -> Integer.compare(a[0], b[0]));        return list.toArray(new int[0][]);    }
    public static void main(String[] args) {        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};        System.out.println(Arrays.deepToString(merge(intervals)));    }}
Output
[[1, 6], [8, 10], [15, 18]]

What this code does

  • Each scan looks at every pair and merges the first overlap it finds, then starts again.
  • Up to n merges times n² pair checks gives O(n³) in the worst case.
  • The result is correct, but sorting first removes all of this repeated searching.

Example 4 · Optimal: sort, then one scan (O(n log n) time, O(n) space)

MergeIntervalsDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class MergeIntervalsDemo {    public static int[][] merge(int[][] intervals) {        if (intervals.length <= 1) return intervals;        Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
        List<int[]> merged = new ArrayList<>();        int[] current = intervals[0];        merged.add(current);
        for (int i = 1; i < intervals.length; i++) {            int[] next = intervals[i];            if (next[0] <= current[1]) {                current[1] = Math.max(current[1], next[1]);            } else {                current = next;                merged.add(current);            }        }        return merged.toArray(new int[merged.size()][]);    }
    public static void main(String[] args) {        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};        int[][] result = merge(intervals);        System.out.println(Arrays.deepToString(result));    }}
Output
[[1, 6], [8, 10], [15, 18]]

What this code does

  • After sorting, overlapping intervals are neighbours, so one scan extending the current interval finishes the job. Repeated pair merging would need many passes.
  • Sorts intervals ascending by start time in O(n log n) time.
  • Maintains reference to the active interval currently being merged.
  • Extends the active interval's end time when next start is within bounds.

After sorting by start time, overlapping intervals form contiguous chains. We maintain a current interval [curStart, curEnd] and scan remaining intervals. If the next interval starts before or when curEnd finishes, they overlap. When an overlap occurs, we extend curEnd to Math.max(curEnd, nextEnd). If the next interval starts strictly after curEnd, no overlap is possible with later intervals. We add the finished interval to results and begin a new current interval. This single linear scan merges all intervals in O(n) time after sorting. Trace merging intervals [[1, 3], [8, 10], [2, 6], [15, 18]]: Sort by start time: [[1, 3], [2, 6], [8, 10], [15, 18]]. Start with [1, 3]. Next is [2, 6]: 2 <= 3, so merge into [1, max(3, 6)] = [1, 6]. Next is [8, 10]: 8 > 6, so commit [1, 6] to results and start [8, 10]. Next is [15, 18]: 15 > 10, commit [8, 10] and start [15, 18]. Final: [[1, 6], [8, 10], [15, 18]].

Find the bug

Find the merge bug

Tap the line that merges wrongly.

Intervals [1, 10] and [2, 4] must give [1, 10].

Round 1 of 2

Custom String Concatenation: Largest Number

Numbers can be joined into the biggest number by sorting them with a custom comparator on the two joined strings. The examples try every order first, then sort.

Example 5 · Brute force: try every order of the numbers (O(n! · n) time, O(n) space)

LargestNumberBrute.javaJava
public class LargestNumberBrute {    static String best = "";
    static void permute(String[] parts, int start) {        if (start == parts.length) {            String joined = String.join("", parts);            if (joined.compareTo(best) > 0) {                best = joined;            }            return;        }        for (int i = start; i < parts.length; i++) {            String t = parts[start]; parts[start] = parts[i]; parts[i] = t;            permute(parts, start + 1);            t = parts[start]; parts[start] = parts[i]; parts[i] = t;        }    }
    public static void main(String[] args) {        String[] parts = {"3", "30", "34", "5", "9"};        permute(parts, 0);        System.out.println("Largest Number: " + best);    }}
Output
Largest Number: 9534330

What this code does

  • permute swaps parts into every possible order, joins them and keeps the biggest string.
  • Five numbers already give 120 orders, and ten numbers give over 3.6 million.
  • The answer 9534330 matches the sorted version, but the cost explodes.

Example 6 · Optimal: sort with a custom comparator (O(n log n) comparisons)

LargestNumberDemo.javaJava
import java.util.Arrays;
public class LargestNumberDemo {    public static String largestNumber(int[] nums) {        String[] strs = new String[nums.length];        for (int i = 0; i < nums.length; i++) {            strs[i] = String.valueOf(nums[i]);        }
        Arrays.sort(strs, (a, b) -> {            String order1 = a + b;            String order2 = b + a;            return order2.compareTo(order1); // Descending order        });
        if (strs[0].equals("0")) return "0";
        StringBuilder sb = new StringBuilder();        for (String s : strs) sb.append(s);        return sb.toString();    }
    public static void main(String[] args) {        int[] nums = {3, 30, 34, 5, 9};        System.out.println("Largest Number: " + largestNumber(nums));    }}
Output
Largest Number: 9534330

What this code does

  • Comparing (a + b) with (b + a) decides every pair locally, so sorting n strings is enough instead of trying n! orders.
  • Converts integers into strings for concatenation comparisons.
  • Compares (b + a) against (a + b) to determine optimal relative order.
  • Sorts strings in descending concatenation order.

For example, given [3, 30, 34, 5, 9], the largest formed number is '9534330'. Brute force generates all all permutations and picks the maximum, which is impossibly slow. We can solve this by sorting the numbers using a custom comparator. Comparing numbers numerically fails: 30 is greater than 3, but 3 must precede 30 because '330' > '303'. Instead, compare two numbers a and b by their concatenated string orders. Compare (b + a) with (a + b) in lexicographical order. If (b + a) exceeds (a + b), number b must precede a in the final arrangement. This custom comparison satisfies strict weak ordering and transitivity. Sorting n strings takes O(n log n) comparisons. An important edge case occurs when the array contains only zeros, like [0, 0]. Sorting yields ['0', '0'], which concatenates to '00'. The algorithm must detect this and return a single '0'.

Predict the output

Which joins first?

Read each snippet and pick what it prints.

Round 1 of 2

String a = "3", b = "30";
System.out.println((a + b).compareTo(b + a) > 0);

Next step

Check your understanding

10 quick questions