14(April) Xoring and Clearing
14. Xoring and Clearing
The problem can be found at the following link: Question Link
Problem Description
You are given an array arr[]
of size (n). You need to do the following:
Calculate the bitwise XOR of each element in the array with its corresponding index (indices start from 0).
After step 1, print the array.
Set all the elements of
arr[]
to zero.Print
arr[]
after setting all elements to zero.
Example 1:
Input:
n = 10
arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Output:
1 3 1 7 1 3 1 15 1 3
0 0 0 0 0 0 0 0 0 0
Explanation:
First, we take the XOR of every element with their indices, like ( (1 \oplus 0), (2 \oplus 1), (3 \oplus 2), (4 \oplus 3) ), and so on.
Now print the resultant array.
Now set all the elements of the array to zero.
Now print the resultant array.
My Approach
XOR Calculation:
Iterate through the array and calculate the bitwise XOR of each element with its corresponding index.
Printing:
Print the array after XOR calculation.
Set to Zero:
Set all the elements of the array to zero.
Printing:
Print the array after setting all elements to zero.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we iterate through the array once to perform XOR calculation and set elements to zero.
Expected Auxiliary Space Complexity: O(1), as we do not use any extra space that grows with the input size.
Code (C++)
class Solution {
public:
void printArr(int n, int arr[]) {
for (int i = 0; i < n; i++) {
std::cout << (arr[i]) << " ";
}
std::cout << std::endl;
}
void setToZero(int n, int arr[]) {
std::fill(arr, arr + n, 0);
}
void xor1ToN(int n, int arr[]) {
for (int i = 0; i < n; i++) {
arr[i] ^= i;
}
}
};
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated