Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Greedy/Greedy

Technique · Interview · medium

Exchange-Argument Sorting (custom comparator)

When the cost of an order changes only through adjacent swaps, compare two items by which order is better when they sit next to each other (a+b vs b+a, ab vs ba, d_a - c_a). Sort by that comparator, then scan or run a DP.

Learn firstGreedy
0%
mastery
0/7 solved
Practise nextLargest Number
IdeaPracticePitfalls

Recognise it

The signal

order items to minimise/maximise a total (concatenation, weighted completion time, energy)

  1. 1Brute force

    Try all n! orders.

  2. 2The observation

    The space of orders.

  3. 3Why it works

    Swapping any adjacent pair that is out of comparator order never makes the solution worse, so sorted order is optimal. The comparator must be a strict weak ordering (transitive).

Reach for it when

  • +for two items, the better order is easy to compute both ways
  • +split items into two groups by a difference (two-city scheduling)

Not when

  • ×the comparator is not transitive (no consistent sort; use DP)
  • ×items interact beyond neighbours (DP over subsets)

Practice

Next

Largest Number

0/7 solved
  • Largest NumberAmazon, UberMedium
  • Two City SchedulingMedium
  • Tasks and DeadlinesCSESMedium
  • The Smallest String ConcatenationCodeforces1700
  • Minimum Initial Energy to Finish TasksHard
  • Programmers and ArtistsCSESHard
  • Complete the Projects (hard version)Codeforces2300

Pitfalls

Misconceptions

  • !sorting numbers by value instead of by concatenation (largest-number)
  • !a non-transitive comparator can crash std::sort
Go deeper3 combinations · resources

Combinations

  • Exchange-Argument Sorting (custom comparator)+0/1 Knapsack

    choose and order projects/rewards with requirement and change values to maximise the count/total

    Exchange-Argument Sorting (custom comparator):
    fixes the processing order (gains first; losses by a_i + b_i descending)
    0/1 Knapsack:
    picks the subset to take, in that order

    Complete the Projects (hard version)Maximum Total Reward Using Operations I

  • Exchange-Argument Sorting (custom comparator)+Top-K Elements

    choose exactly a items for role A and b items for role B, maximising the total

    Exchange-Argument Sorting (custom comparator):
    sort by a_i - b_i so some prefix goes to group A and the rest to group B
    Top-K Elements:
    a heap keeps the best a values in the prefix and the best b values in the suffix

    Programmers and Artists

  • Exchange-Argument Sorting (custom comparator)+LCS / Two-Sequence

    match points on a line to capacity-limited targets minimising the total distance

    Exchange-Argument Sorting (custom comparator):
    sort both robots and factories; an optimal matching never crosses
    LCS / Two-Sequence:
    two-sequence DP: dp[i][j] = robots i.. assigned to factories j..

    Minimum Total Distance Traveled

Resources

  • Greedy Algorithms with SortingUSACO Guide · course
  • Greedy Algorithms (chapter)Jeff Erickson · book
  • Exchange arguments (sorting with dp)Errichto · blog
  • Algorithms playlistAbdul Bari · video
  • Competitive Programmer's HandbookAntti Laaksonen · book
TodayReviewPatternsProblems