28- Sort Array By Parity
The problem can be found at the following link: Question Link
My Approach
Initialize an integer variable
j
to 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
if
condition (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
j
variable by 1 to prepare for the next even element placement.Continue iterating through the elements of the
nums
vector, repeating steps 4-6 for each element.Once the loop finishes, the
nums
vector 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++)
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