Compute the XOR of all integers from M to N inclusive

Quick Overview

Compute the bitwise XOR of every integer from m to n inclusive, where the bounds can reach one billion, so a simple loop is too slow. It tests reasoning about XOR properties and turning a range query into prefix values that can be computed in constant time.

Compute the XOR of all integers from M to N inclusive

Company: Tesla

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

Given two integers `m` and `n`, compute the XOR of all integers from `m` to `n` (inclusive). That is, return `m XOR (m+1) XOR (m+2) XOR ... XOR n`. Your solution must handle large values of `m` and `n` efficiently. ### Function Signature ```python def xor_range(m: int, n: int) -> int: ``` ### Constraints - `0 <= m <= n <= 10^9` ### Examples ```text Input: m = 3, n = 9 Output: 2 ``` The XOR chain is 3 XOR 4 = 7, 7 XOR 5 = 2, 2 XOR 6 = 4, 4 XOR 7 = 3, 3 XOR 8 = 11, and 11 XOR 9 = 2. ```text Input: m = 5, n = 5 Output: 5 ``` When `m` equals `n`, the range holds a single number, so the result is that number. ```text Input: m = 0, n = 6 Output: 7 ``` The running XOR is 0, 1, 3, 0, 4, 1, 7 after each of 0 through 6, so the final value is 7.

Overview: Compute the bitwise XOR of every integer from m to n inclusive, where the bounds can reach one billion, so a simple loop is too slow. It tests reasoning about XOR properties and turning a range query into prefix values that can be computed in constant time.

Tesla logo
Tesla
Nov 24, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Given two integers m and n, compute the XOR of all integers from m to n (inclusive).

That is, return m XOR (m+1) XOR (m+2) XOR ... XOR n.

Your solution must handle large values of m and n efficiently.

Function Signature

def xor_range(m: int, n: int) -> int:

Constraints

  • 0 <= m <= n <= 10^9

Examples

Input: m = 3, n = 9
Output: 2

The XOR chain is 3 XOR 4 = 7, 7 XOR 5 = 2, 2 XOR 6 = 4, 4 XOR 7 = 3, 3 XOR 8 = 11, and 11 XOR 9 = 2.

Input: m = 5, n = 5
Output: 5

When m equals n, the range holds a single number, so the result is that number.

Input: m = 0, n = 6
Output: 7

The running XOR is 0, 1, 3, 0, 4, 1, 7 after each of 0 through 6, so the final value is 7.