Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

When is sorting allowed?

Sorting moves values around, so their positions change. If a question asks for positions, like "the first index where", that is a problem. But if it asks how many pairs there are, or whether a pair exists, only the values matter, and you are free to sort first.

It is like counting how many couples at a party can share a cab: who stands where doesn't matter.

Asks about values or counts? Sort freely.
Asks for original positions? Sorting loses them. Use a map instead.
Pairs within a budget of 10: [8, 1, 6, 3, 9] sorted to [1, 3, 6, 8, 9]target = 10
1
0
3
1
6
2
8
3
9
4
leftright

1 + 9 = 10 fits. 1 also fits with 3, 6 and 8: count = 4. Left moves right.

Move 1 of 5

Sorting unlocks two pointers

You met this walk in Arrays. On a sorted list, if the cheapest and the dearest of the two ends fit the budget together, then the cheapest also fits with every value between them, because those are smaller. Count them all at once and move the left end up. If they don't fit, the right end is too dear for anyone, so move the right end down.

Fits? add all the values between the ends to the count, then move left up.
Too big? move right down.
In code
prices.sort()
count = 0
lo, hi = 0, len(prices) - 1
while lo < hi:
    if prices[lo] + prices[hi] <= budget:
        count += hi - lo
        lo += 1
    else:
        hi -= 1
return count