28- Sort Array By Parity
The problem can be found at the following link: Question Link
My Approach
Initialize an integer variable
jto 0. This variable will keep track of the position where the next even number should be placed in the array.Within the loop, check if the current element at
nums[i]is even. You can do this by using the bitwise AND operation with 1, i.e.,!(nums[i] & 1). If the result is true, it means the current element is even.Inside the
ifcondition (when the current element is even), perform a swap operation betweennums[i]andnums[j]. This swaps the current even element with the element at positionj,effectively moving all even elements to the front of the array.Increment the
jvariable by 1 to prepare for the next even element placement.Continue iterating through the elements of the
numsvector, repeating steps 4-6 for each element.Once the loop finishes, the
numsvector will be sorted with all even elements at the beginning and all odd elements at the end.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)Auxiliary Space Complexity:
O(1)
Code (C++)
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& nums) {
int j=0;
for(int i=0;i<nums.size();i++){
if(!(nums[i]&1)){
swap(nums[i],nums[j]);
j++;
}
}
return nums;
}
};
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the rishabhv12/Daily-Leetcode-Solution repository.
Last updated
Was this helpful?