Lowest Inversion Count When Merging Two Strings
Hard · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Given two strings primary (of length m) and secondary (of length n) consisting of lowercase English letters, weave them into a single string merged of length m + n that consumes every character of both inputs while keeping the characters of primary in their original left-to-right order and keeping the characters of secondary in their original left-to-right order.
Alphabetically earlier letters hold higher priority ('a' highest, 'z' lowest). Whenever a lower-priority character sits ahead of a higher-priority character in merged—that is, an index pair 0 <= x < y < m + n with merged[x] > merged[y]—that pair contributes 1 conflict to the merge cost. For instance, "xbd" contains 2 conflicts ('x' > 'b' and 'x' > 'd').
Implement:
def min_merge_conflicts(primary: str, secondary: str) -> int:
Compute and return the smallest total conflict count achievable across all valid interleavings of primary and secondary.
Details to observe:
- Every pair of indices (x, y) with x < y and merged[x] > merged[y] adds 1 to the count, including pairs whose two characters came from the same input string.
- Matching letters (merged[x] == merged[y]) never conflict with one another.
- Return only the minimum integer count, not a merged string.
Examples
Example 1
Input: primary = "cb", secondary = "d"
Output: 1
The three valid interleavings are "dcb" (3 conflicts: d > c, d > b, c > b), "cdb" (2 conflicts: c > b, d > b), and "cbd" (1 conflict: c > b). No interleaving can eliminate the internal 'c' > 'b' pair inside primary.
Example 2
Input: primary = "eb", secondary = "dc"
Output: 4
Merging into "dceb" produces 4 conflicts (d > c, d > b, c > b, and e > b). "debc" and "ebdc" also produce 4, while "decb" (5), "edbc" (5), and "edcb" (6) are worse.
Example 3
Input: primary = "mm", secondary = "em"
Output: 0
Choosing 'e' from secondary first yields "emmm". Since 'e' < 'm' and identical 'm' letters never conflict, the conflict count is 0.
Constraints
1 <= len(primary) <= 10001 <= len(secondary) <= 1000primaryandsecondarycontain only lowercase English letters'a'through'z'.- At
m = n = 1000, the count never exceeds2000 * 1999 / 2 = 1,999,000, which fits within a 32-bit signed integer.
Step-by-step walkthrough
Restate the problem and what a conflict means
We receive two lowercase strings,
primary(lengthm) andsecondary(lengthn), with1 <= m, n <= 1000. We must interleave them into one string of lengthm + nthat consumes every character of both inputs while preserving each input string's own left-to-right character order.Alphabetically smaller letters hold higher priority (
'a'highest,'z'lowest). A conflict is any index pairx < yin the merged string withmerged[x] > merged[y]alphabetically (an inversion):primary = "cb", secondary = "d" -> 3 valid interleavings: "dcb": (d > c), (d > b), (c > b) -> 3 conflicts "cdb": (c > b), (d > b) -> 2 conflicts "cbd": (c > b) -> 1 conflict (optimal)Notice two important rules: - Equal letters never conflict (
'm'before'm'adds0). - Same-string pairs still count:'c'before'b'in"cb"contributes1conflict to every merge because'c'must always precede'b'.Brute force and why the merge-sort greedy rule fails
Trying every valid interleaving means choosing
mslots out ofm + nforprimary, which is(m + n) choose mstrings — form = n = 1000, that number has over 600 digits!A very tempting shortcut is the merge-sort rule: "at each step, look at the two front letters and append whichever one is smaller." Watch how that greedy rule gets trapped on
primary = "xac"andsecondary = "w":Front letters are 'x' (from "xac") and 'w' (from "w"): Greedy picks 'w' first -> "wxac": conflicts: (w > a), (w > c), (x > a), (x > c) = 4 conflicts! Wait to put 'w' at the very end -> "xacw": conflicts: (x > a), (x > c), (x > w) = 3 conflicts!Picking
'w'before'x'avoided1conflict with'x', but exposed'w'to two tiny letters ('a'and'c') hiding behind'x'! Because a local choice depends on future characters, we need dynamic programming to compare both options at every state.Key insight: count conflicts when the later letter lands
Imagine building the merged string one character at a time from left to right. Whenever we append a character
chat the end of the current prefix, how many new conflicts doeschcreate? Exactly one for every already-placed character that is strictly greater thanch! Every conflicting pair(x, y)is counted once — at the exact moment its right charactermerged[y]is placed.Here is the observation that makes dynamic programming work cleanly:
Suppose we have already placed primary[:i] and secondary[:j] in SOME interleaved order: placed so far: [ ... some mix of primary[:i] and secondary[:j] ... ] + next_char |<---- exact same multiset of i + j characters ---->|No matter how
primary[:i]andsecondary[:j]were interleaved among themselves, the collection of letters already sitting to the left is alwaysprimary[:i]plussecondary[:j]! So the new conflicts caused by the(i + j)-th character depend only on(i, j), never on the path taken to reach(i, j).Define
dp[i][j]as the minimum conflicts amongprimary[:i]andsecondary[:j]. Looking at whichever letter was placed last at positioni + j: - Takeprimary[i - 1]last (afterprimary[:i - 1]andsecondary[:j]):dp[i - 1][j] + (chars in primary[:i - 1] > primary[i - 1]) + (chars in secondary[:j] > primary[i - 1])- Takesecondary[j - 1]last (afterprimary[:i]andsecondary[:j - 1]):dp[i][j - 1] + (chars in primary[:i] > secondary[j - 1]) + (chars in secondary[:j - 1] > secondary[j - 1])And
dp[i][j]is simply theminof those two choices!Precompute "how many earlier letters are greater" in `O(1)`
To evaluate each DP cell in
O(1)time instead of rescanning prefixes, we leverage the 26-letter alphabet. For a stringtext, we buildtable[k][code]= how many characters intext[:k]are strictly greater thancode(0 = 'a', ..., 25 = 'z').After updating the letter frequency
freqfortext[:k], scanningcodedownward from25('z') to0('a') accumulatesstrictly_greater_so_farin one 26-step pass:Prefix "eb" -> freq has e:1, b:1 code = 25..5 ('z'..'f'): greater = 0 code = 4 ('e'): row['e'] = 0, then greater += 1 (seen 'e') -> 1 code = 3..2 ('d'..'c'): row['d'] = 1, row['c'] = 1 ('e' > 'd' and 'e' > 'c') code = 1 ('b'): row['b'] = 1, then greater += 1 (seen 'b') -> 2 code = 0 ('a'): row['a'] = 2 ('e' > 'a' and 'b' > 'a')def build_greater_counts(text: str) -> List[List[int]]: """Build table where table[k][char_code] = count of letters in text[:k] strictly > char_code.""" # table[0] represents the empty prefix text[:0], which has 0 letters above every character. table: List[List[int]] = [[0] * 26] # freq[c]: how many times letter code c (0='a' .. 25='z') has appeared in the prefix so far freq = [0] * 26 for ch in text: freq[ord(ch) - ord("a")] += 1 prefix_row = [0] * 26 # Sweep from 'z' (25) down to 'a' (0) accumulating letters strictly larger than code. strictly_greater_so_far = 0 for code in range(25, -1, -1): prefix_row[code] = strictly_greater_so_far strictly_greater_so_far += freq[code] table.append(prefix_row) return tableFill the DP table row by row in `O(n)` memory
Notice that computing
dp[i][j]only readsdp[i - 1][j](directly above) anddp[i][j - 1](immediately to the left). So we only need two 1D lists of lengthn + 1:prev_row(dp[i - 1]) andcurr_row(dp[i]).- Row
0(i = 0) places only prefixes ofsecondary. - Column
0(j = 0) places only prefixes ofprimary.
def min_merge_conflicts(primary: str, secondary: str) -> int: m = len(primary) n = len(secondary) # Convert characters once to integer codes 0..25 ('a' -> 0, ..., 'z' -> 25). primary_codes = [ord(ch) - ord("a") for ch in primary] secondary_codes = [ord(ch) - ord("a") for ch in secondary] # Precompute O(1) lookups for how many characters in any prefix are strictly > char_code. greater_in_primary = build_greater_counts(primary) greater_in_secondary = build_greater_counts(secondary) # prev_row[j] holds dp[i - 1][j]: minimum conflicts when merging primary[:i - 1] and secondary[:j]. # Base row i = 0 places only secondary[:j] in order. prev_row = [0] * (n + 1) for j in range(1, n + 1): s_char = secondary_codes[j - 1] prev_row[j] = prev_row[j - 1] + greater_in_secondary[j - 1][s_char] # Fill rows i = 1 .. m one row at a time. for i in range(1, m + 1): p_char = primary_codes[i - 1] # Conflicts between primary[i - 1] and earlier characters inside primary[:i - 1]. primary_self_conflicts = greater_in_primary[i - 1][p_char] curr_row = [0] * (n + 1) # Column j = 0 places only primary[:i] in order. curr_row[0] = prev_row[0] + primary_self_conflicts greater_primary_i = greater_in_primary[i] for j in range(1, n + 1): # Option 1: Place primary[i - 1] last, right after primary[:i - 1] + secondary[:j]. take_primary = ( prev_row[j] + primary_self_conflicts + greater_in_secondary[j][p_char] ) # Option 2: Place secondary[j - 1] last, right after primary[:i] + secondary[:j - 1]. s_char = secondary_codes[j - 1] take_secondary = ( curr_row[j - 1] + greater_primary_i[s_char] + greater_in_secondary[j - 1][s_char] ) curr_row[j] = min(take_primary, take_secondary) prev_row = curr_row return prev_row[n]- Row
Walk through Example 2 on the DP grid
Let's trace
primary = "eb"(m = 2) andsecondary = "dc"(n = 2):DP table dp[i][j]: j = 0 ("") j = 1 ("d") j = 2 ("dc") i = 0 ("") 0 0 1 ("dc": d > c) i = 1 ("e") 0 0 1 ("dce": e after dc adds 0) i = 2 ("eb") 1 2 4 ("dceb": b after dce adds d>b, c>b, e>b)Check the bottom-right cell
dp[2][2]: -take_primary(append'b'after optimal merge of"e"+"dc", which had costdp[1][2] = 1): earlier letters are{'e', 'd', 'c'}; all three ('e','d', and'c') are strictly> 'b', so1 + 3 = 4. -take_secondary(append'c'after optimal merge of"eb"+"d", which had costdp[2][1] = 2): earlier letters are{'e', 'b', 'd'}; two of them ('e'and'd') are strictly> 'c', so2 + 2 = 4. -min(4, 4) = 4(achieved by"dceb","debc", or"ebdc").Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def build_greater_counts(text: str) -> List[List[int]]: """Build table where table[k][char_code] = count of letters in text[:k] strictly > char_code.""" # table[0] represents the empty prefix text[:0], which has 0 letters above every character. table: List[List[int]] = [[0] * 26] # freq[c]: how many times letter code c (0='a' .. 25='z') has appeared in the prefix so far freq = [0] * 26 for ch in text: freq[ord(ch) - ord("a")] += 1 prefix_row = [0] * 26 # Sweep from 'z' (25) down to 'a' (0) accumulating letters strictly larger than code. strictly_greater_so_far = 0 for code in range(25, -1, -1): prefix_row[code] = strictly_greater_so_far strictly_greater_so_far += freq[code] table.append(prefix_row) return table def min_merge_conflicts(primary: str, secondary: str) -> int: m = len(primary) n = len(secondary) # Convert characters once to integer codes 0..25 ('a' -> 0, ..., 'z' -> 25). primary_codes = [ord(ch) - ord("a") for ch in primary] secondary_codes = [ord(ch) - ord("a") for ch in secondary] # Precompute O(1) lookups for how many characters in any prefix are strictly > char_code. greater_in_primary = build_greater_counts(primary) greater_in_secondary = build_greater_counts(secondary) # prev_row[j] holds dp[i - 1][j]: minimum conflicts when merging primary[:i - 1] and secondary[:j]. # Base row i = 0 places only secondary[:j] in order. prev_row = [0] * (n + 1) for j in range(1, n + 1): s_char = secondary_codes[j - 1] prev_row[j] = prev_row[j - 1] + greater_in_secondary[j - 1][s_char] # Fill rows i = 1 .. m one row at a time. for i in range(1, m + 1): p_char = primary_codes[i - 1] # Conflicts between primary[i - 1] and earlier characters inside primary[:i - 1]. primary_self_conflicts = greater_in_primary[i - 1][p_char] curr_row = [0] * (n + 1) # Column j = 0 places only primary[:i] in order. curr_row[0] = prev_row[0] + primary_self_conflicts greater_primary_i = greater_in_primary[i] for j in range(1, n + 1): # Option 1: Place primary[i - 1] last, right after primary[:i - 1] + secondary[:j]. take_primary = ( prev_row[j] + primary_self_conflicts + greater_in_secondary[j][p_char] ) # Option 2: Place secondary[j - 1] last, right after primary[:i] + secondary[:j - 1]. s_char = secondary_codes[j - 1] take_secondary = ( curr_row[j - 1] + greater_primary_i[s_char] + greater_in_secondary[j - 1][s_char] ) curr_row[j] = min(take_primary, take_secondary) prev_row = curr_row return prev_row[n]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine merging two single-file airport boarding lines (primary and secondary) into one jetway where passengers hold boarding groups 'a' (highest priority) through 'z' (lowest priority): nobody can jump ahead of someone in their own line, and every time a lower-priority letter steps onto the plane ahead of a higher-priority letter, we tally one conflict (also known as an inversion, a pair of positions x < y where merged[x] > merged[y]). The key insight is to build the merged line from front to back and count each conflict at the exact moment the later letter boards: if i people from primary and j people from secondary have already boarded, the exact same group of i + j letters is already on the plane no matter what order they boarded in! That makes the problem ideal for dynamic programming (DP) (solving a problem by storing optimal answers to smaller prefix subproblems (i, j) in a table so no subproblem is ever solved twice).
Why do simpler approaches fail? Enumerating every valid interleaving (a combined sequence that preserves each input string's internal order) takes (m + n) choose m tries, which explodes astronomically long before m, n = 1000. Meanwhile, a greedy algorithm (making whichever local move looks best right now, like always picking the smaller front letter as in merge sort) gets tricked by "xac" and "w": picking 'w' before 'x' saves 1 conflict against 'x' right now, but costs 2 conflicts against the 'a' and 'c' waiting right behind 'x' ("wxac" has 4 conflicts, whereas "xacw" has 3).
Let's trace primary = "cb" and secondary = "d":
dp[i][j] = min conflicts when merging primary[:i] and secondary[:j]
start: dp[0][0] = 0
row 0: dp[0][1] ("d") = 0 (nothing before 'd')
col 0: dp[1][0] ("c") = 0, dp[2][0] ("cb") = 1 ('c' > 'b')
dp[1][1] (merge "c" and "d"):
- put 'c' last after "d": 0 + (# in "d" > 'c' = 1) = 1 ("dc")
- put 'd' last after "c": 0 + (# in "c" > 'd' = 0) = 0 ("cd")
-> dp[1][1] = 0
dp[2][1] (merge "cb" and "d"):
- put 'b' last after ("c" + "d"): dp[1][1] + (# in "c"+"d" > 'b' = 2) = 0 + 2 = 2 ("cdb")
- put 'd' last after "cb": dp[2][0] + (# in "cb" > 'd' = 0) = 1 + 0 = 1 ("cbd")
-> dp[2][1] = 1
Complexity
- Time:
O(m * n + 26 * (m + n)), because building the two prefix tables (lookup arrays storing cumulative letter counts for every prefix0 .. length) takes 26 operations per character acrossm + ncharacters, and filling the(m + 1) * (n + 1)DP grid performs twoO(1)table lookups per cell (about10^6tiny iterations atm = n = 1000). - Space:
O(26 * (m + n) + n), becausegreater_in_primaryandgreater_in_secondarystore26integers per prefix, while the DP uses a space-optimized rolling row (keeping onlyprev_rowandcurr_rowof sizen + 1instead of the fullm * nmatrix).
Edge cases
- Identical characters (e.g.,
"aaa"and"aaa"): conflicts require strict inequality (merged[x] > merged[y]), sobuild_greater_countscounts only strictly larger letters and returns0. - Unavoidable conflicts inside a single string (e.g.,
primary = "ba",secondary = "c"):'b'must always appear before'a', soprimary_self_conflictsadds1,'c'goes at the end for0extra conflicts, and the answer is1. - Already sorted strings (e.g.,
"abc"and"abd"): interleaving them in sorted order creates zero inversions, returning0. - Single-character inputs (e.g.,
"z"and"a"): placing'a'before'z'gives"az"with0conflicts. - Maximum size (
m = n = 1000): The worst-case conflict count is(2000 * 1999) / 2 = 1,999,000, which fits comfortably inside a standard 32-bit integer, and iterative loops avoid Python's 1000-frame recursion limit.
Common mistakes
- Using the merge-sort greedy rule ("take the smaller front character"): Works only when both input strings are already sorted; on unsorted inputs like
"xac"and"w", a large front letter ('x') can shield much smaller letters ('a','c') behind it. - Forgetting same-string conflicts (or double-counting them): The problem counts every pair
x < yinmerged, including pairs where both characters came fromprimaryor both came fromsecondary. Including bothgreater_in_primaryandgreater_in_secondarywhen placing each character counts every pair once. - Counting
>=instead of strictly>: Inbuild_greater_counts,prefix_row[code]must be recorded before addingfreq[code]tostrictly_greater_so_far, otherwise equal letters falsely conflict with one another. - Off-by-one prefix indices in transitions: When
primary[i - 1]is placed atdp[i][j],i - 1characters ofprimaryandjcharacters ofsecondaryprecede it (greater_in_primary[i - 1]andgreater_in_secondary[j]), notgreater_in_primary[i]. - Writing top-down recursion (
@lru_cache) in Python: Atm = n = 1000, recursion reaches depthm + n = 2000and crashes withRecursionErrorunlesssys.setrecursionlimitis raised; bottom-up row iteration uses zero recursion stack.
Alternative approaches
- Separate internal conflicts from cross-string conflicts: Because the inversions within
primaryalone and withinsecondaryalone are identical in every valid interleaving, you can count those two internal inversion totals once up front inO(26 * (m + n))time and letdp[i][j]minimize only the cross-string conflicts (greater_in_secondary[j][p_char]fortake_primaryandgreater_in_primary[i][s_char]fortake_secondary), adding the fixed internal sum at the end. Both formulas compute the exact same numbers.
Follow-up questions
- How would you modify the DP so it also outputs an interleaved string achieving the optimal count? Keep the full
(m + 1) * (n + 1)DP table (or a booleanchose_primary[i][j]table) inO(m * n)space instead of discarding earlier rows. Starting from(i, j) = (m, n), check whetherdp[i][j]came fromtake_primary(appendprimary[i - 1]and step to(i - 1, j)) ortake_secondary(appendsecondary[j - 1]and step to(i, j - 1)), then reverse the collected characters inO(m + n)time. - Suppose the two inputs are integer lists with values up to
10^9rather than lowercase English strings. How can you keep the runtime nearO(m * n)? A 26-column prefix table would no longer fit, so separate the two conflict types: first count internal inversions insideprimaryandsecondaryinO((m + n) log(m + n))time using merge sort or a Fenwick tree (a binary indexed tree array that supports prefix-sum queries and point updates inO(log k)time). Then during theO(m * n)DP, maintain cross-counts incrementally on the fly — asjadvances across rowi, increment a running counter wheneversecondary[j - 1] > primary[i - 1], and maintain a 1D arraygreater_p[j]incremented wheneverprimary[i - 1] > secondary[j - 1]— solving the general integer problem inO(m * n + (m + n) log(m + n))time andO(m + n)space! - Does this dynamic programming formulation extend to merging
ksequences simultaneously, and what happens to the complexity? Yes, in principle: the DP state becomes ak-tuple of prefix lengths(i_1, i_2, ..., i_k)withkchoices for which sequence supplies the last element, because the multiset of placed elements still depends only on thekprefix lengths. However, the state count is(L_1 + 1) * (L_2 + 1) * ... * (L_k + 1), which grows exponentially ink, making exact DP practical only whenkand the sequence lengths are small.
Follow-up questions
- How would you modify the DP so it also outputs an interleaved string achieving the optimal count?
- Suppose the two inputs are integer lists with values up to `10^9` rather than lowercase English strings. How can you keep the runtime near `O(m * n)`?
- Does this dynamic programming formulation extend to merging `k` sequences simultaneously, and what happens to the complexity?
Similar questions
- Place One Hub to Minimize Maximum Grid Distance
- Evaluate Large Batches of Variable Ratio Queries
- SQL Daily Active Users and Distinct Palindromic Subsequences
- Single-Domain BFS Web Crawler
- In-Memory Inverted Sentence Index
- Design an O(1) LRU Cache
More Amazon interview questions
- Minimizing Worst-Case Grid Distance with One Extra Hub Medium
- Consolidate Overlapping Intervals Medium
- Amazon Final-Round Intern Behavioral Prompts Easy Pro
- Amazon Onsite Leadership Principles Behavioral Loop Medium Pro
- Leadership and Generative AI Behavioral Screen Easy Pro
- Amazon Software Engineering Intern Behavioral Screen Hard Pro
- Core Engineering Ownership and Leadership Prompts Medium Pro
- Data Science Behavioral Scenarios on Amazon Leadership Principles Medium Pro
- Target Sum Pair and Longest Unique Substring Medium Pro
- String Rearrangement, K-Way List Merge, and Random-Pointer Cloning Medium Pro