KatInterview

Minimum Disorder When Interleaving Two Job Queues

Dynamic ProgrammingAuto-graded · 26 test cases
HardAuto-gradedDynamic Programmingdynamic-programmingstringsprefix-counts

Last updated

Interleave two letter strings while keeping each one's order, minimizing out-of-order pairs; tests 2D prefix DP with O(1) transition costs from alphabet-count tables.

Two print servers each hold a line of waiting jobs. Each line is a string of lowercase letters, and each letter is the urgency of that job: 'a' is the most urgent and 'z' the least urgent.

You will build one combined schedule that contains every job from first (length m) and every job from second (length n) exactly once. Within the schedule, the jobs that came from first must keep their original relative order, and the same holds for the jobs from second. In other words, the schedule is an interleaving of the two strings.

A pair of schedule positions x < y is misordered if schedule[x] > schedule[y] in alphabetical order, so a less urgent job runs before a more urgent one. Jobs with equal letters are never misordered with each other.

For instance, the schedule "zab" has 2 misordered pairs: z before a, and z before b.

Return the smallest possible number of misordered pairs over all valid interleavings.

Function

def min_interleave_disorder(first: str, second: str) -> int:

Rules

  • Every character of both inputs is used exactly once.
  • Characters from the same input keep their original relative order.
  • Misordered pairs are counted over all pairs of positions in the final schedule, including two characters that both came from the same input. Those pairs are the same in every valid interleaving.
  • Return only the minimum count, not the schedule.

Constraints

  • 1 <= len(first) <= 1000
  • 1 <= len(second) <= 1000
  • Both strings consist only of lowercase English letters.
  • The answer fits in a 32-bit signed integer.

Examples

Example 1

Input: min_interleave_disorder('fd', 'e')

Output: 2

Example 2

Input: min_interleave_disorder('hg', 'pc')

Output: 4

Example 3

Input: min_interleave_disorder('k', 'k')

Output: 0

Hints

Hint 1

Split the total into pairs inside `first`, pairs inside `second`, and pairs with one character from each. Only the last group depends on how you interleave.

Hint 2

Model an interleaving as a monotone path on an `(m+1) x (n+1)` grid. Let `dp[i][j]` be the fewest cross pairs after placing the first `i` characters of `first` and the first `j` of `second`.

Hint 3

When you append a character, the new cross pairs it creates equal the number of already-placed characters from the other string that are strictly greater than it. Precompute, for each prefix of each string, how many characters exceed each letter, so each transition is O(1).