Leetcode 1486: XOR Operation in an Array

Category : Easy

Problem

Given an integer n and an integer start.

Define an array nums where nums[i] = start + 2*i (0-indexed) and n == nums.length.

Return the bitwise XOR of all elements of nums.

https://leetcode.com/problems/xor-operation-in-an-array/

Examples

Example 1:

Example 2:

Example 3:

Example 4:

Constraints

  • 1 <= n <= 1000
  • 0 <= start <= 1000
  • n == nums.length

Solution Approach

In this problem, we just need to perform XOR operation on a set of elements but the elements we need to find ourselves. The calculation of elements is straightforward and it will start from the value in start variable and it increases by 2 with every step.

Coming to the solution of the problem we initialise our answer variable with the value of start. We are initialising with start and not 0 or 1 because the initial value may change the answer and give the error in the result. Then we loop through the numbers starting with 1 to n (given in the problem). We ran the loop starting from 1 because we already initialised answer variable with start hence we have used up 0th index.

We perform XOR operation using ‘^’ on all the elements and store it in the answer variable. In the end, we return the value of the same answer variable’s value as the answer.

Solution code

For more Leetcode explained solutions visit Leetcode Solutions. If you like capture the flag challenges visit here.

Check out my socials below in the footer. Feel free to ask any doubts in the comment section or contact me via Contact page I will surely respond. Happy Leetcoding 

Leave a Comment

Your email address will not be published. Required fields are marked *