- construct the array of calculated values
- iterate through that array, accumulating the XOR value
- return the XOR result
π€What Did I Struggle With?
- rusty on implementation and application of bit manupulation
π‘ Explanation of Solution
The problem requires finding the XOR of elements in a specific sequence generated based on the given formula. The XOR operation can be applied iteratively to all elements since it is both associative and commutative, making it possible to compute the result efficiently.
β Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n) - can be done in O(1) with inplace computation instead of a result array
π» Implementation of Solution
class Solution {public: int xorOperation(int n, int start) { vector<int> arr(n, 0); for(int i=0; i < n; i++) { arr[i] = start + 2 * i; } int result = 0; for (int num : arr) { result ^= num; // XOR with cumulative result } return result; }};