Find a Value of a Mysterious Function Closest to Target - Problem
You are given an integer array arr and an integer target. You need to find the values l and r such that 0 <= l, r < arr.length that make the value |func(arr, l, r) - target| minimum possible.
The mysterious function func(arr, l, r) returns the bitwise XOR of all elements in the subarray from index l to index r (inclusive).
Return the minimum possible value of |func(arr, l, r) - target|.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [1,2,3,4], target = 6
›
Output:
1
💡 Note:
We can choose l = 1 and r = 2. func(arr, 1, 2) = 2 ⊕ 3 = 1. |1 - 6| = 5. We can also choose l = 2 and r = 3. func(arr, 2, 3) = 3 ⊕ 4 = 7. |7 - 6| = 1. The minimum is 1.
Example 2 — Single Element
$
Input:
arr = [9,12,3,7,15], target = 5
›
Output:
2
💡 Note:
We can choose l = 3 and r = 3. func(arr, 3, 3) = 7. |7 - 5| = 2. We can also try other subarrays but this gives the minimum difference of 2.
Example 3 — Target Match
$
Input:
arr = [4,6,7,9], target = 6
›
Output:
0
💡 Note:
We can choose l = 1 and r = 1. func(arr, 1, 1) = 6. |6 - 6| = 0. Perfect match!
Constraints
- 1 ≤ arr.length ≤ 105
- 0 ≤ arr[i] ≤ 108
- 0 ≤ target ≤ 108
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,2,3,4] and target = 6
2
Process
Calculate XOR for all subarrays
3
Output
Return minimum |XOR - target|
Key Takeaway
🎯 Key Insight: XOR has unique properties - we need to check all possible subarrays to find the one with XOR value closest to target
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code