LeetCode 905: Sort Array By Parity Solution
Master LeetCode problem 905 (Sort Array By Parity), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
905. Sort Array By Parity
Problem Explanation
Explanation
To solve this problem, we can use a two-pointer approach where we maintain two pointers left and right. The left pointer starts at the beginning of the array and moves to the right, while the right pointer starts at the end of the array and moves to the left.
We swap elements at these pointers if they are at the wrong place (even number on the right side or odd number on the left side). The process continues until the left pointer is greater than or equal to the right pointer.
- Time complexity: O(n) where n is the number of elements in the array.
- Space complexity: O(1) constant extra space is used.
Solution Code
class Solution {
public int[] sortArrayByParity(int[] nums) {
int left = 0;
int right = nums.length - 1;
while (left < right) {
if (nums[left] % 2 != 0 && nums[right] % 2 == 0) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
if (nums[left] % 2 == 0) {
left++;
}
if (nums[right] % 2 != 0) {
right--;
}
}
return nums;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 905 (Sort Array By Parity)?
This page provides optimized solutions for LeetCode problem 905 (Sort Array By Parity) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 905 (Sort Array By Parity)?
The time complexity for LeetCode 905 (Sort Array By Parity) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 905 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 905 in Java, C++, or Python.