LeetCode – XOR Operation in an Array

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

Solution: Even if the problem mentions to build an array, we don’t really need one as the output is an integer. To resolve the problem I’m iterating n times and applying XOR start + 2 * i on the output directly. (same thing as we would build an array and apply XOR for each element of the array (element = start + 2 * i).

var xorOperation = function(n, start) {
    var output = 0;

    for(var i = 0; i < n; i++)
        output = output ^ start + 2 * i;

    return output;

Time Complexity: O(n)

Leave a Reply

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