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) <= 1000
  • 1 <= len(secondary) <= 1000
  • primary and secondary contain only lowercase English letters 'a' through 'z'.
  • At m = n = 1000, the count never exceeds 2000 * 1999 / 2 = 1,999,000, which fits within a 32-bit signed integer.

Step-by-step walkthrough

  1. Restate the problem and what a conflict means

    We receive two lowercase strings, primary (length m) and secondary (length n), with 1 <= m, n <= 1000. We must interleave them into one string of length m + n that 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 pair x < y in the merged string with merged[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' adds 0). - Same-string pairs still count: 'c' before 'b' in "cb" contributes 1 conflict to every merge because 'c' must always precede 'b'.

  2. Brute force and why the merge-sort greedy rule fails

    Trying every valid interleaving means choosing m slots out of m + n for primary, which is (m + n) choose m strings — for m = 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" and secondary = "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' avoided 1 conflict 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.

  3. 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 ch at the end of the current prefix, how many new conflicts does ch create? Exactly one for every already-placed character that is strictly greater than ch! Every conflicting pair (x, y) is counted once — at the exact moment its right character merged[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] and secondary[:j] were interleaved among themselves, the collection of letters already sitting to the left is always primary[:i] plus secondary[: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 among primary[:i] and secondary[:j]. Looking at whichever letter was placed last at position i + j: - Take primary[i - 1] last (after primary[:i - 1] and secondary[:j]): dp[i - 1][j] + (chars in primary[:i - 1] > primary[i - 1]) + (chars in secondary[:j] > primary[i - 1]) - Take secondary[j - 1] last (after primary[:i] and secondary[: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 the min of those two choices!

  4. 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 string text, we build table[k][code] = how many characters in text[:k] are strictly greater than code (0 = 'a', ..., 25 = 'z').

    After updating the letter frequency freq for text[:k], scanning code downward from 25 ('z') to 0 ('a') accumulates strictly_greater_so_far in 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 table
    
  5. Fill the DP table row by row in `O(n)` memory

    Notice that computing dp[i][j] only reads dp[i - 1][j] (directly above) and dp[i][j - 1] (immediately to the left). So we only need two 1D lists of length n + 1: prev_row (dp[i - 1]) and curr_row (dp[i]).

    • Row 0 (i = 0) places only prefixes of secondary.
    • Column 0 (j = 0) places only prefixes of primary.
    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]
    
  6. Walk through Example 2 on the DP grid

    Let's trace primary = "eb" (m = 2) and secondary = "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 cost dp[1][2] = 1): earlier letters are {'e', 'd', 'c'}; all three ('e', 'd', and 'c') are strictly > 'b', so 1 + 3 = 4. - take_secondary (append 'c' after optimal merge of "eb" + "d", which had cost dp[2][1] = 2): earlier letters are {'e', 'b', 'd'}; two of them ('e' and 'd') are strictly > 'c', so 2 + 2 = 4. - min(4, 4) = 4 (achieved by "dceb", "debc", or "ebdc").

  7. 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 prefix 0 .. length) takes 26 operations per character across m + n characters, and filling the (m + 1) * (n + 1) DP grid performs two O(1) table lookups per cell (about 10^6 tiny iterations at m = n = 1000).
  • Space: O(26 * (m + n) + n), because greater_in_primary and greater_in_secondary store 26 integers per prefix, while the DP uses a space-optimized rolling row (keeping only prev_row and curr_row of size n + 1 instead of the full m * n matrix).

Edge cases

  • Identical characters (e.g., "aaa" and "aaa"): conflicts require strict inequality (merged[x] > merged[y]), so build_greater_counts counts only strictly larger letters and returns 0.
  • Unavoidable conflicts inside a single string (e.g., primary = "ba", secondary = "c"): 'b' must always appear before 'a', so primary_self_conflicts adds 1, 'c' goes at the end for 0 extra conflicts, and the answer is 1.
  • Already sorted strings (e.g., "abc" and "abd"): interleaving them in sorted order creates zero inversions, returning 0.
  • Single-character inputs (e.g., "z" and "a"): placing 'a' before 'z' gives "az" with 0 conflicts.
  • 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 < y in merged, including pairs where both characters came from primary or both came from secondary. Including both greater_in_primary and greater_in_secondary when placing each character counts every pair once.
  • Counting >= instead of strictly >: In build_greater_counts, prefix_row[code] must be recorded before adding freq[code] to strictly_greater_so_far, otherwise equal letters falsely conflict with one another.
  • Off-by-one prefix indices in transitions: When primary[i - 1] is placed at dp[i][j], i - 1 characters of primary and j characters of secondary precede it (greater_in_primary[i - 1] and greater_in_secondary[j]), not greater_in_primary[i].
  • Writing top-down recursion (@lru_cache) in Python: At m = n = 1000, recursion reaches depth m + n = 2000 and crashes with RecursionError unless sys.setrecursionlimit is raised; bottom-up row iteration uses zero recursion stack.

Alternative approaches

  • Separate internal conflicts from cross-string conflicts: Because the inversions within primary alone and within secondary alone are identical in every valid interleaving, you can count those two internal inversion totals once up front in O(26 * (m + n)) time and let dp[i][j] minimize only the cross-string conflicts (greater_in_secondary[j][p_char] for take_primary and greater_in_primary[i][s_char] for take_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 boolean chose_primary[i][j] table) in O(m * n) space instead of discarding earlier rows. Starting from (i, j) = (m, n), check whether dp[i][j] came from take_primary (append primary[i - 1] and step to (i - 1, j)) or take_secondary (append secondary[j - 1] and step to (i, j - 1)), then reverse the collected characters in O(m + n) time.
  • 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)? A 26-column prefix table would no longer fit, so separate the two conflict types: first count internal inversions inside primary and secondary in O((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 in O(log k) time). Then during the O(m * n) DP, maintain cross-counts incrementally on the fly — as j advances across row i, increment a running counter whenever secondary[j - 1] > primary[i - 1], and maintain a 1D array greater_p[j] incremented whenever primary[i - 1] > secondary[j - 1] — solving the general integer problem in O(m * n + (m + n) log(m + n)) time and O(m + n) space!
  • Does this dynamic programming formulation extend to merging k sequences simultaneously, and what happens to the complexity? Yes, in principle: the DP state becomes a k-tuple of prefix lengths (i_1, i_2, ..., i_k) with k choices for which sequence supplies the last element, because the multiset of placed elements still depends only on the k prefix lengths. However, the state count is (L_1 + 1) * (L_2 + 1) * ... * (L_k + 1), which grows exponentially in k, making exact DP practical only when k and the sequence lengths are small.

Follow-up questions

Similar questions

More Amazon interview questions

All 653 Amazon questions →