Dynamic Programming21 sections · 916 units
Open in Course

Assignment - Implementation

O(n × 2^n)

Here is the full solution for minimum XOR sum:

function minXorSum(nums1, nums2)
    n := length of nums1
    INF := large number
    dp := array of size 2^n, filled with INF
    dp[0] := 0
    for mask := 0 to 2^n - 1
        if dp[mask] = INF then
            continue
        k := popcount(mask)
        if k >= n then
            continue
        for j := 0 to n - 1
            if (mask >> j) & 1 = 1 then
                continue
            newMask := mask | (1 << j)
            cost := nums1[k] XOR nums2[j]
            dp[newMask] := min(dp[newMask], dp[mask] + cost)
    return dp[2^n - 1]

The trick: popcount(mask)\text{popcount}(\text{mask}) tells you how many elements of nums1 have been assigned. If the mask has kk bits set, you are assigning nums1[kk] next. This eliminates the need for a second dimension in the DP.

Time: O(n2n)O(n \cdot 2^n). Space: O(2n)O(2^n).