Problem · Array

Bitwise XOR Subsequences

Learn this problem
MediumJPMorgan ChaseOA

Problem statement

A subsequence of an array is formed by removing zero or more elements without changing the order of the remaining elements.

A subsequence is valid when the bitwise XOR of every pair of adjacent elements equals k. A subsequence of length 1 is invalid, regardless of the value of k, because it contains no adjacent pair.

Given an integer array arr of size n and an integer k, return the length of the longest valid subsequence.

Function

maxSubsequenceLength(n: int, arr: int[], k: int) → int

Examples

Example 1

n = 5arr = [2, 1, 3, 5, 2]k = 2return = 2

The subsequence [1, 3] is valid because 1 XOR 3 = 2. No valid subsequence is longer than 2. For example, [2, 1, 3] is invalid because 2 XOR 1 is not 2.

Example 2

n = 3arr = [1, 1, 1]k = 0return = 3

The entire array is valid because every adjacent pair is (1, 1) and 1 XOR 1 = 0.

Constraints

  • 1 <= n <= 10^5
  • 0 <= arr[i] <= 10^6
  • 0 <= k <= 10^6

More JPMorgan Chase problems

drafts saved locally
public int maxSubsequenceLength(int n, int[] arr, int k) {
  // write your code here
}
n5
arr[2, 1, 3, 5, 2]
k2
expected2
checking account