KatInterview

Maximize Total Distinct Values Across Two Arrays

Arrays & HashingAuto-graded · 17 test cases
HardAuto-gradedArrays & Hashingbacktrackinggreedyfrequency-counting

Last updated

Tests greedy reasoning, frequency counting, and backtracking search to maximize the combined distinct-value count across two arrays given a limited swap budget.

Problem

You have two integer arrays row and col, both of length n, and a non-negative integer budget. In one operation you may pick any index i and exchange row[i] with col[i]. You may do this at most budget times (using the same index more than once is allowed, but swapping an index back cancels the original swap, so only the net parity per index matters).

After all operations are done, let D(row) be the number of distinct values in row and D(col) be the number of distinct values in col. Return the maximum possible value of D(row) + D(col).

Notes

  • A swap at index i where row[i] == col[i] has no observable effect on either array, so it never helps.
  • The budget applies to the total number of swaps performed, not to the number of distinct indices touched.
  • The answer when budget = 0 is simply D(row) + D(col) computed on the original arrays.

Constraints

  • 1 <= n <= 10^5
  • 0 <= budget <= n
  • 1 <= row[i], col[i] <= 10^6

Examples

Example 1

Input: maximize_distinct([1, 2, 3], [1, 2, 4], 1)

Output: 6

Example 2

Input: maximize_distinct([1, 1], [2, 2], 0)

Output: 2

Hints

Hint 1

Positions where row[i] == col[i] can never be improved by swapping — ignore them to reduce the search space.

Hint 2

Think about what a swap at index i actually changes: it moves row[i] to col and col[i] to row. Model the contribution of each index independently, then consider how swapping one index can affect the distinctness counts of both endpoints at once.

Hint 3

Use backtracking with incremental set tracking: at each index, try keeping the pair or swapping it (if budget allows and row[i] != col[i]), adding values only when they are not already present, and undoing exactly those additions on the way back.