oneby7

Tries Tries over bits

429. Maximum XOR of Two Numbers in an Array

Medium

You are given an array of non-negative integers nums. Choose two indexes i and j with i ≤ j, and return the largest value that nums[i] XOR nums[j] can take.

XOR, written ^ in code, compares two numbers bit by bit. A bit of the result is 1 when exactly one of the two numbers has that bit set. For example, 12 ^ 2 = 14, because 12 is 1100 in binary, 2 is 0010, and they differ in three bits.

i and j may be the same index, so an array with one element gives 0.

Example 1

Input: nums = [12, 5, 9, 2, 7]

Output: 14

Explanation: Two pairs reach 14: 12 ^ 2 and 9 ^ 7. No pair reaches 15, since 12 would need 3 as its partner and 9 would need 6.

Example 2

Input: nums = [37]

Output: 0

Explanation: The only choice is i = j = 0, and 37 ^ 37 = 0.

Example 3

Input: nums = [1073741824, 1000000000, 7]

Output: 2073741824

Explanation: 1073741824 is 230, and 1000000000 is smaller, so the two share no set bit. Their XOR is the same as their sum.

Check your understanding

Work out the answer for this input before you write any code.

nums = [9, 6, 14]

Constraints

  • 1 ≤ nums.length ≤ 2 × 105
  • 0 ≤ nums[i] ≤ 231 − 1

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.