Merge two ordered commit streams with the fewest priority inversions
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Online Assessment
Overview: Merge two commit-priority strings while preserving each input order and minimizing inverted pairs. Account for equal priorities and unavoidable internal conflicts, and derive an efficient prefix-state dynamic program.
Read the full Amazon Software Engineer interview experience this question came from
Constraints
- `1 <= len(primary), len(secondary) <= 1000`.
- Both inputs contain only lowercase ASCII letters.
- The answer is at most `1999000`, which fits a signed 32-bit integer.
Examples
Input: ('zc', 'd')
Expected Output: 2
Explanation: The optimal merge can start from either stream.
Input: ('ab', 'ab')
Expected Output: 0
Explanation: A monotone merge preserves both orders with no conflicts.
Hints
- When appending a commit, only larger letters already placed create new conflicts.
- A partial merge uses a prefix of each stream.