LeetCode 922: Sort Array By Parity II Solution
Master LeetCode problem 922 (Sort Array By Parity II), 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.
922. Sort Array By Parity II
Problem Explanation
Explanation
To solve this problem, we can use a two-pointer approach. We will maintain two pointers, one for even indices and one for odd indices. We iterate through the array and whenever we find an element at the wrong position (even number at an odd index or odd number at an even index), we swap it with the element at the correct position. This way, we can ensure that the array is sorted such that even numbers are at even indices and odd numbers are at odd indices.
- Time complexity: O(n) where n is the number of elements in the array.
- Space complexity: O(1) since we are performing the sorting in-place.
Solution Code
class Solution {
public int[] sortArrayByParityII(int[] nums) {
int odd = 1, even = 0;
while (even < nums.length && odd < nums.length) {
while (even < nums.length && nums[even] % 2 == 0) {
even += 2;
}
while (odd < nums.length && nums[odd] % 2 == 1) {
odd += 2;
}
if (even < nums.length && odd < nums.length) {
int temp = nums[even];
nums[even] = nums[odd];
nums[odd] = temp;
}
}
return nums;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 922 (Sort Array By Parity II)?
This page provides optimized solutions for LeetCode problem 922 (Sort Array By Parity II) 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 922 (Sort Array By Parity II)?
The time complexity for LeetCode 922 (Sort Array By Parity II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 922 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 922 in Java, C++, or Python.