Even And Odd Geeks For Geeks
Problem Link:
https://practice.geeksforgeeks.org/problems/even-and-odd/1#
(It is also the problem of the day for 26-05-2022)
Solution:
class Solution {
static void reArrange(int[] arr, int n) {
int arr1[]=new int[arr.length/2];//odd element array
int arr2[]=new int[arr.length/2];//even element array
int index1=0;
int index2=0;
for(int i=0;i<n;i++){
if((arr[i]&1)==0){
arr2[index1++]=arr[i];
}
else{
arr1[index2++]=arr[i];
}
}
Time Complexity: O(N)[GFG Time: 0.52/1.59]
Space Complexity: O(N)[Array is used]
Auxiliary Space: O(N/2)[Two small subarrays of half-sized of original array size is used]
Total Test Cases:221
Approach Used:
1. Traverse the whole array and see whether the element is odd or even.
2. If the element is odd then add in an array named arr1 and if it is even then add it to arr2.
3. Later modify the original array by taking one element from arr1 and arr2.
For checking whether the element is even or odd we are using the bitwise operator "&"
Reason for using & instead of a modulus operator:
It is fast
1. It compares the bits of number and sees the last bit.
2. If the last bit is 1 then the number is odd or if the last bit is 0 then the number is even.
example:
3&1 then 011 & 01 == 001 ie last bit is 1=> number is odd.
4&1 then 100 & 01 == 000 ie last bit is 0=> number is even.
"Thanks For Reading.😇"
"Share Further To Increase Knowledge Treasure.😊"
Comments
Post a Comment