FastPrepMaximize Binary XOR with a Set-Bit Limit

Maximize Binary XOR with a Set-Bit Limit

JP Morgan Chase logoJP Morgan Chase● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

You are given a binary string x, its required bitLength, and an integer maxSet. Construct a binary string y of exactly bitLength bits with at most maxSet one-bits so that the numeric value of x XOR y is maximized.

Return y, preserving leading zeros.

Function

maximizeXor(x: String, bitLength: int, maxSet: int) → String

Examples

Example 1

x = "10100"bitLength = 5maxSet = 2return = "01010"

Set the two highest-order positions where x has zero, producing XOR value 11110.

Example 2

x = "10100"bitLength = 5maxSet = 5return = "01011"

All zero-bits of x can be flipped; extra one-bits would reduce the XOR value.

Example 3

x = "111"bitLength = 3maxSet = 2return = "000"

Any one-bit in y would turn a high XOR bit off.

Constraints

  • 1 <= bitLength <= 200000
  • x.length == bitLength and x contains only 0 and 1.
  • 0 <= maxSet <= bitLength.

More JP Morgan Chase problems

See JP Morgan Chase hiring insights
public String maximizeXor(String x, int bitLength, int maxSet) {
    // Write your code here.
}
x"10100"
bitLength5
maxSet2
expected"01010"
Checking account…