Interview Questions/Coding/Count Misordered Coin Pairs

Count Misordered Coin Pairs

Preview mode. Log in to edit, run, submit, and save progress.

Hard

Count Misordered Coin Pairs

You are given a single stack of coins, represented by an integer array coins from top to bottom. Each coin has an integer value written on it. A pair of coins is considered misordered if a coin closer to the top has a greater value than a coin below it. Formally, for two positions i and j, the pair is misordered if: i < j and coins[i] > coins[j] Return the total number of misordered coin pairs in the stack. Equal-valued coins are not considered misordered.

Examples

Example 1
Input:
coins = [2,4,1,3,5]
Output:
3

Explanation: The misordered pairs are (2,1), (4,1), and (4,3).

Approach hint

Compare the problem with counting how far the stack is from sorted order.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

solution.cpp