712176. Find XOR of numbers from L to R.

Easy

Find XOR of numbers from L to R

Slug: find-xor-of-numbers-from-l-to-r

Difficulty: Easy

Id: 712176

Summary

Given a range [L, R] and an array of integers arr[], the task is to find the XOR (exclusive OR) of all numbers in this range. The problem requires you to write an efficient algorithm that calculates the XOR of all numbers from L to R.

Detailed Explanation

The key idea behind solving this problem is to use the property of XOR operation, which states that a ^ a = 0 and a ^ b = c implies b ^ a = c. This allows us to subtract the XOR of the numbers up to L-1 from the XOR of all numbers up to R to get the desired result.

Here's the step-by-step breakdown:

  1. Calculate the XOR of all numbers up to L-1 and store it in a variable xor_L.
  2. Calculate the XOR of all numbers up to R and store it in another variable xor_R.
  3. The XOR of all numbers from L to R is xor_R ^ xor_L.

To calculate xor_L and xor_R, you can use a simple loop that iterates over the array, updating the XOR value at each step.

Time complexity: O(R - L + 1), as we need to iterate over the range [L, R]. Space complexity: O(1), as we only need a few variables to store the intermediate results.

Optimized Solutions

Java

View on GeeksforGeeks
public int findXOR(int[] arr, int L, int R) {
    int xor_L = 0;
    for (int i = 0; i < L; i++) {
        xor_L ^= arr[i];
    }
    int xor_R = 0;
    for (int i = L - 1; i <= R; i++) {
        xor_R ^= arr[i];
    }
    return xor_R ^ xor_L;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.