Partition Array to Minimize XOR - Problem

You are given an integer array nums and an integer k. Your task is to partition nums into k non-empty subarrays.

For each subarray, compute the bitwise XOR of all its elements. Return the minimum possible value of the maximum XOR among these k subarrays.

A subarray is a contiguous part of an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4], k = 2
Output: 4
💡 Note: Optimal partition: [1,2,3] with XOR = 0, and [4] with XOR = 4. Maximum XOR = max(0,4) = 4.
Example 2 — Single Elements
$ Input: nums = [5,6,7], k = 3
Output: 7
💡 Note: Each element forms its own partition: [5], [6], [7]. Maximum XOR = max(5,6,7) = 7.
Example 3 — All Together
$ Input: nums = [1,1,1,1], k = 1
Output: 0
💡 Note: All elements in one partition: [1,1,1,1]. XOR = 1⊕1⊕1⊕1 = 0.

Constraints

  • 1 ≤ nums.length ≤ 103
  • 1 ≤ nums[i] ≤ 106
  • 1 ≤ k ≤ nums.length

Visualization

Tap to expand
Partition Array to Minimize XOR INPUT Array nums: 1 i=0 2 i=1 3 i=2 4 i=3 k = 2 (partitions) nums = [1, 2, 3, 4] Binary Values: 1 = 001 2 = 010 3 = 011 4 = 100 Find best split point to minimize max XOR ALGORITHM STEPS 1 Try All Splits Test each partition point 2 Compute XOR XOR each subarray 3 Track Maximum Find max XOR per split 4 Minimize Result Choose best partition Split Options (k=2): [1] | [2,3,4] XOR: 1, 5 max=5 [1,2] | [3,4] XOR: 3, 7 max=7 [1,2,3] | [4] XOR: 0, 4 max=4 Best: min(5,7,4) = 4 FINAL RESULT Optimal Partition: [1, 2, 3] [4] XOR Calculations: 1 XOR 2 XOR 3 = 0 4 = 4 max(0, 4) = 4 Output: 4 [OK] Minimum maximum XOR achieved with this partition Key Insight: Greedy approach: Try all possible partition points for k subarrays. For k=2, there are (n-1) ways to split. Compute XOR for each subarray using prefix XOR for O(1) queries. Track the minimum of maximum XORs across all partitions. XOR property: a XOR a = 0, so XOR(i,j) = prefix[j] XOR prefix[i-1]. Time complexity: O(n^k) for general k. TutorialsPoint - Partition Array to Minimize XOR | Greedy Approach
Asked in
Google 15 Microsoft 12 Amazon 8
8.6K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen