Katkat

Maximize Distinct Values with Cross-Array Swaps

Akuna CapitalSoftware Engineer · Technical Screen

Last updated

This problem tests greedy strategy optimization and frequency counting to maximize the count of unique elements across two arrays after a limited number of swaps.

Problem Statement

You are given two arrays A and B of length n, and an integer k. You are allowed to perform at most k swaps, where a single swap consists of choosing one index i (0 <= i < n) and swapping A[i] and B[i].

Your goal is to maximize the sum of distinct elements present in A plus the distinct elements present in B. Specifically, maximize count_distinct(A) + count_distinct(B) after at most k swaps.

Function Signature

def maximize_distinct(A, B, k):

Constraints

  • n is up to 10^5.
  • k is between 0 and n.
  • Array elements are integers between 1 and 10^6.

Example 1

Input: A = [1, 2, 3], B = [1, 2, 4], k = 1 Output: 5 Explanation: Swapping index 2 gives A = [1, 2, 4] and B = [1, 2, 3]. Distinct in A is 3, distinct in B is 3, total 6. Wait, after swapping index 2, A becomes [1, 2, 4] (3 distinct) and B becomes [1, 2, 3] (3 distinct). Total = 6.

Example 2

Input: A = [1, 1], B = [2, 2], k = 0 Output: 2 Explanation: No swaps possible. A has {1} (count 1), B has {2} (count 1). Total = 2.

Edge Cases

  • k = 0 (no changes allowed).
  • All elements are the same across both arrays.
  • A[i] == B[i] for all i (swapping yields no difference).

Hints

Hint 1

Categorize indices into two groups: those where A[i] == B[i] and those where A[i] != B[i].

Hint 2

Swapping indices where A[i] == B[i] never changes the set of distinct elements; focus your swaps only on indices where A[i] != B[i].

Hint 3

Use a greedy approach: identify swaps that increase the number of unique elements by removing duplicates between the two sets or adding new values to the union.

Follow-up questions

  • How does your algorithm change if we want to maximize the size of the union of A and B instead of the sum of distinct counts?
  • What if we were allowed to swap any index i with any index j across the two arrays, instead of only at the same index?
  • How can you optimize space complexity if the range of values in A and B is extremely large (e.g., 64-bit integers)?