Minimize Inversions in a Prefix Tree Problem
Description
LeetCode Problem 4077.
You are given an array words of n unique strings containing only lowercase English letters from 'a' to 'j'. You are also given an integer array target containing each index from 0 to n - 1 exactly once.
Build a prefix tree from words:
- The root represents the empty string
"". - Each other node represents a different non-empty prefix of a word. The parent of a node is the prefix obtained by removing its last character.
- The node representing the complete word
words[i]is marked with indexi. A marked node may also have children.
You may choose the order of the children of each node independently. You cannot change which node is a child's parent.
Traverse the tree starting at the root. When visiting a node, first record its index if it is marked. Then visit its children in the chosen order, completing the traversal of each child before moving to the next. This is a pre-order traversal.
The recorded indices form an array traversal of length n. Let pos[i] be the position of index i in target.
An inversion is a pair of positions (a, b) such that 0 <= a < b < n and pos[traversal[a]] > pos[traversal[b]].
Return the minimum possible number of inversions over all choices of child orderings.
Example 1:

Input: words = ["bad","bag","fig","fed"], target = [3,1,0,2]
Output: 2
Explanation:
Visit the root's "f" child before its "b" child. Within the "f" branch, visit "fed" before "fig". Within the "b" branch, visit "bag" before "bad".
This produces traversal = [3,2,1,0]:
Traversal position Word index Word Position in target
0 3 "fed" 0
1 2 "fig" 3
2 1 "bag" 1
3 0 "bad" 2
The positions in target are [0,3,1,2]. The inversions are the pairs of traversal positions (1,2) and (1,3), since 3 > 1 and 3 > 2.
No child ordering produces fewer than 2 inversions.
Example 2:
Input: words = ["ab","ac","ba","bc"], target = [0,3,1,2]
Output: 1
Explanation:
Visit the root's "a" child before its "b" child. Within these branches, visit "ab" before "ac", and "bc" before "ba".
This produces traversal = [0,1,3,2]:
Traversal position Word index Word Position in target
0 0 "ab" 0
1 1 "ac" 2
2 3 "bc" 1
3 2 "ba" 3
The positions in target are [0,2,1,3]. The only inversion is the pair of traversal positions (1,2), since 2 > 1.
No child ordering produces zero inversions.
Constraints:
1 <= n == words.length <= 10^41 <= words[i].length <= 20words[i]contains only lowercase English letters from'a'to'j'- All
words[i]are unique 0 <= target[i] <= n - 1targetis a permutation of integers from 0 ton - 1
Solution
Approach: Per-node ordering with bitmask DP
Count the inversions by the lowest common ancestor v of the two words involved:
- If one of them is the word at
vitself, it is visited first, so the pair is an inversion exactly when the word atvhas a larger target position than the other word. This cost does not depend on any choice. - Otherwise the two words lie in different child subtrees of
v, and the pair only depends on which of the two children is visited first, not on the order inside the subtrees. Letc[i][j]be the number of pairs(x, y)withxin childi,yin childjandpos[x] > pos[y]; visitingibeforejcostsc[i][j].
So each node is an independent problem: order its children (at most 10, the letters a to j) to minimize the sum of c[i][j] over all pairs with i before j. With a bitmask dp[mask] = the cheapest cost of placing the children in mask first, adding child j after them costs the sum of c[i][j] over i in mask. That is O(2^k * k) per node with k children.
To compute c, sort the words, so that every subtree is a contiguous range, and handle the nodes by recursion. At a node, list the subtree's words with their target position and child index, sort them by position, and sweep: for each word, add the number of already seen words of every other child to c[child][other].
Complexity: the lists over all nodes contain O(n * L) entries in total (L = word length), so the sweeps cost O(n * L * 10) plus the sorting; the bitmask DPs cost O(2^10 * 10) for each node with 10 children, and there are at most n / 9 of them.
from bisect import bisect_left
class Solution:
def minInversions(self, words: List[str], target: List[int]) -> int:
n = len(words)
pos = [0] * n
for p, i in enumerate(target):
pos[i] = p
order = sorted(range(n), key=lambda i: words[i])
INF = float("inf")
def solve(lo: int, hi: int, d: int) -> int:
# order[lo:hi] are the words that share a prefix of length d (the node)
own = -1
if len(words[order[lo]]) == d: # the node itself is a word, it sorts first
own = order[lo]
lo += 1
groups = []
i = lo
while i < hi:
ch = words[order[i]][d]
j = i
while j < hi and words[order[j]][d] == ch:
j += 1
groups.append((i, j))
i = j
res = 0
elems = []
for g, (a, b) in enumerate(groups):
res += solve(a, b, d + 1)
for t in range(a, b):
elems.append((pos[order[t]], g))
elems.sort()
if own >= 0: # the node's own word is visited first
res += bisect_left(elems, (pos[own], -1))
k = len(groups)
if k < 2:
return res
# c[i][j]: pairs (x in child i, y in child j) with pos[x] > pos[y], i.e. the cost of visiting i before j
c = [[0] * k for _ in range(k)]
seen = [0] * k
for _, g in elems:
row = c[g]
for j in range(k):
row[j] += seen[j]
seen[g] += 1
full = (1 << k) - 1
# cs[mask][j]: the cost of putting child j after all the children in mask
cs = [[0] * k]
for mask in range(1, full + 1):
cs.append([x + y for x, y in zip(cs[mask & (mask - 1)], c[(mask & -mask).bit_length() - 1])])
dp = [INF] * (full + 1)
dp[0] = 0
for mask in range(full):
cur = dp[mask]
row = cs[mask]
for j in range(k):
if not mask >> j & 1:
nxt = mask | 1 << j
v = cur + row[j]
if v < dp[nxt]:
dp[nxt] = v
return res + dp[full]
return solve(0, n, 0)