922. Sort Array By Parity II LeetCode Solution

In this guide, you will get 922. Sort Array By Parity II LeetCode Solution with the best time and space complexity. The solution to Sort Array By Parity II problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Sort Array By Parity II solution in C++
  4. Sort Array By Parity II solution in Java
  5. Sort Array By Parity II solution in Python
  6. Additional Resources
922. Sort Array By Parity II LeetCode Solution image

Problem Statement of Sort Array By Parity II

Given an array of integers nums, half of the integers in nums are odd, and the other half are even.
Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.
Return any answer array that satisfies this condition.

Example 1:

Input: nums = [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

Example 2:

Input: nums = [2,3]
Output: [2,3]

Constraints:

2 <= nums.length <= 2 * 104
nums.length is even.
Half of the integers in nums are even.
0 <= nums[i] <= 1000

Follow Up: Could you solve it in-place?

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

922. Sort Array By Parity II LeetCode Solution in C++

class Solution {
 public:
  vector<int> sortArrayByParityII(vector<int>& nums) {
    const int n = nums.size();

    for (int i = 0, j = 1; i < n; i += 2, j += 2) {
      while (i < n && nums[i] % 2 == 0)
        i += 2;
      while (j < n && nums[j] % 2 == 1)
        j += 2;
      if (i < n)
        swap(nums[i], nums[j]);
    }

    return nums;
  }
};
/* code provided by PROGIEZ */

922. Sort Array By Parity II LeetCode Solution in Java

class Solution {
  public int[] sortArrayByParityII(int[] nums) {
    final int n = nums.length;

    for (int i = 0, j = 1; i < n; i += 2, j += 2) {
      while (i < n && nums[i] % 2 == 0)
        i += 2;
      while (j < n && nums[j] % 2 == 1)
        j += 2;
      if (i < n) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
      }
    }

    return nums;
  }
}
// code provided by PROGIEZ

922. Sort Array By Parity II LeetCode Solution in Python

class Solution:
  def sortArrayByParityII(self, nums: list[int]) -> list[int]:
    n = len(nums)

    i = 0
    j = 1
    while i < n:
      while i < n and nums[i] % 2 == 0:
        i += 2
      while j < n and nums[j] % 2 == 1:
        j += 2
      if i < n:
        nums[i], nums[j] = nums[j], nums[i]

    return nums
# code by PROGIEZ

Additional Resources

See also  143. Reorder List LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.