XOR Operation in an Array – C++ Solution


class Solution {
 public:
  int xorOperation(int n, int start) {
    int ans = 0;
    for (int i = 0; i < n; ++i)
      ans ^= start + 2 * i;
    return ans;
  }
};
    

Problem Description

So, you think you can just throw a bunch of numbers into an array and expect them to behave? Well, think again! The problem at hand is the "XOR Operation in an Array." Imagine you have a party, and everyone is invited, but instead of mingling, they just keep XORing their numbers. The task is to find out what the final result of all that XORing will be.

In simpler terms, given an integer n and an integer start, you need to create an array of size n where the i-th element is defined as start + 2 * i. Then, you need to compute the XOR of all these elements.

It's like trying to figure out who ate the last slice of pizza at a party—everyone's pointing fingers, but in the end, you just want to know who the culprit is!

Approach

The approach here is straightforward. We initialize a variable ans to zero and loop through n times. In each iteration, we calculate the value of the current element using the formula start + 2 * i and XOR it with ans. By the end of the loop, ans will hold the final XOR value of all the elements in the array.

Time and Space Complexity

Time Complexity: O(n) - We loop through the array once.

Space Complexity: O(1) - We only use a constant amount of space for the variable ans.

Real-World Example

Imagine you’re at a family reunion, and everyone brings their own unique dish. Each dish has a secret ingredient (the number). You want to find out what the combined secret ingredient is after everyone has mixed their dishes together. The XOR operation helps you figure out the final flavor of the reunion feast without actually tasting every dish!

Similar Problems

If you enjoyed this problem, you might also like these: