Minimum Disorder When Interleaving Two Job Queues
Dynamic ProgrammingAuto-graded · 26 test casesLast 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) <= 10001 <= 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).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every misordered pair falls into one of three groups: both characters from first, both from second, or one from each. The relative order of two characters from the same string never changes, so the first two groups contribute a fixed amount. We count them once for each string by sweeping left to right and, for each character, adding the number of earlier characters that are strictly greater (tracked with a 26-entry frequency array).
The only quantity that depends on the interleaving is the number of cross pairs. We minimize it with a DP over a grid. Let dp[i][j] be the minimum number of cross pairs after placing the first i characters of first and the first j characters of second in some valid order.
Appending a character next to the placed prefix adds cross pairs equal to the number of already-placed characters from the other string that are strictly greater than it, because each of those now sits earlier than a more urgent job. Which characters are already placed matters only through these counts (the prefixes), not through the order they were placed in, so the DP is valid:
- Place
first[i]next:dp[i+1][j] = dp[i][j] + (number of chars in second[:j] greater than first[i]) - Place
second[j]next:dp[i][j+1] = dp[i][j] + (number of chars in first[:i] greater than second[j])
To make each transition O(1), we precompute for each prefix of each string a 26-entry table giving, for every letter, how many characters in that prefix are strictly greater. Each row is built from a running frequency array and a suffix sum over the alphabet.
The answer is the fixed within-string count plus dp[m][n]. Only the previous DP row is needed, so memory for the DP is O(n).
Why it is correct
The decomposition counts every pair exactly once. The DP explores every interleaving (every monotone grid path), and its transition cost is exactly the number of new cross pairs created by the appended character, so the minimum over paths equals the minimum cross count. A local greedy rule (always take the smaller front character) is not enough, so the DP compares both choices at every cell.
Complexity
- Time: O(m * n + 26 * (m + n)).
- Space: O(26 * (m + n) + n).
Reference solution
def min_interleave_disorder(first: str, second: str) -> int:
a = [ord(ch) - 97 for ch in first]
b = [ord(ch) - 97 for ch in second]
m, n = len(a), len(b)
def internal_inversions(codes):
seen = [0] * 26
total = 0
for c in codes:
total += sum(seen[c + 1:])
seen[c] += 1
return total
def greater_table(codes):
# table[k][c] = number of characters among codes[:k] that are > c
table = [[0] * 26 for _ in range(len(codes) + 1)]
freq = [0] * 26
for k, code in enumerate(codes, 1):
freq[code] += 1
running = 0
row = table[k]
for c in range(25, -1, -1):
row[c] = running
running += freq[c]
return table
gt_a = greater_table(a)
gt_b = greater_table(b)
# Row i = 0: only characters of `second` placed, no cross pairs.
dp = [0] * (n + 1)
for i in range(1, m + 1):
ca = a[i - 1]
new = [0] * (n + 1) # j = 0: only characters of `first` placed
row_a = gt_a[i]
for j in range(1, n + 1):
take_a = dp[j] + gt_b[j][ca]
take_b = new[j - 1] + row_a[b[j - 1]]
new[j] = take_a if take_a < take_b else take_b
dp = new
return internal_inversions(a) + internal_inversions(b) + dp[n]