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: 0
💡 Note: We can choose l = 1 and r = 3. func(arr, 1, 3) = 2 ⊕ 3 ⊕ 4 = 6. |6 - 6| = 0. Perfect match!
Example 2 — Single Element
$ Input: arr = [9,12,3,7,15], target = 5
Output: 1
💡 Note: We can choose l = 2 and r = 3. func(arr, 2, 3) = 3 ⊕ 7 = 4. |4 - 5| = 1. This gives the minimum difference of 1.
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
Find Mysterious Function Closest to Target INPUT Array arr: 1 i=0 2 i=1 3 i=2 4 i=3 Target: 6 Mysterious Function: func(arr, l, r) = arr[l] XOR arr[l+1] ... XOR arr[r] Goal: Minimize |func(arr,l,r) - target| ALGORITHM STEPS 1 Track XOR Values Use set to store unique XORs 2 Iterate Array For each element, extend XORs 3 Update Min Distance Check |xor - target| each time 4 Return Minimum Best difference found Incremental XOR Values: i=0: {1} i=1: {2, 1 XOR 2=3} i=2: {3, 3 XOR 3=0, 1 XOR 2 XOR 3=0} i=3: {4, 0 XOR 4=4, 7} XOR=7 gives |7-6|=1 (from subarray [1,2,3,4] XOR) 1 XOR 2 XOR 3 XOR 4 = 4 FINAL RESULT Minimum Difference Found: 1 Best XOR value: 7 |7 - 6| = 1 Optimal Subarray: 1 2 4 l=0, r=2: 1 XOR 2 XOR 4 = 7 OK - Verified! Output: 1 Key Insight: XOR has a property: as we extend subarrays ending at index i, the number of distinct XOR values is limited (at most O(log max_element)). Instead of checking all O(n^2) subarrays, we incrementally compute XORs by extending previous results, reducing time complexity significantly. This is the Incremental XOR approach. TutorialsPoint - Find a Value of a Mysterious Function Closest to Target | Optimized - Incremental XOR
Asked in
Google 45 Facebook 32 Microsoft 28
23.4K Views
Medium Frequency
~35 min Avg. Time
892 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