Sansa and XOR HackerRank Solution

Sansa and XOR HackerRank Solution

In this Sansa and XOR HackerRank solution, Sansa has an array. She wants to find the value obtained by XOR-ing the contiguous subarrays, followed by XOR-ing the values thus obtained. Determine this value.

Sansa and XOR HackerRank Solution

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

Problem Solution in JavaScript

function sansaXor(arr: number[]): number {
    // Write your code here
    const arrLength = arr.length
    let result = 0
    if(arrLength%2===0){
        return 0
    }else{
        for(let i=0;i<arrLength;i+=2){
             result = result ^ arr[i]
        }
        return result
    }
}

Problem Solution in Python

def sansaXor(arr):
    n = len(arr)
    if n % 2 == 0:
        return 0
    res = 0
    for i in range(n):
        if i % 2 == 0:
            res = res ^ arr[i]
    return res

Problem Solution in C#

public static int sansaXor(List<int> arr)
{
  int output = 0;


  if (arr.Count % 2 == 0)
    return output;


  for (int i = 0; i < arr.Count; i += 2)
    output ^= arr[i];


  return output;
}

Problem Solution in Java

    public static int sansaXor(List<Integer> arr) {
    // Write your code here
        int len = arr.size();
        if (len % 2 == 0) {
            return 0;
        }
       
        int midIdx = arr.size() / 2;
        int xorRes = 0;
        for (int i = 0; i < arr.size(); i += 2) {
            xorRes ^= arr.get(i);
        }
       
        return xorRes;
    }

Problem Solution in C++

int sansaXor(vector<int> arr) {
    int ans = 0;
    if(arr.size() % 2 == 0) {
        return 0;
    }
    else {
        for(unsigned long i = 0; i < arr.size(); i += 2) {
            ans = ans ^ arr[i];
        }
    }
    return ans;
}
Solve original Problem on HackerRank here. Checkout more HackerRank Problems