905. Sort Array By Parity LeetCode Solution
In this guide, you will get 905. Sort Array By Parity LeetCode Solution with the best time and space complexity. The solution to Sort Array By Parity 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
- Problem Statement
- Complexity Analysis
- Sort Array By Parity solution in C++
- Sort Array By Parity solution in Java
- Sort Array By Parity solution in Python
- Additional Resources
Problem Statement of Sort Array By Parity
Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.
Example 1:
Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Example 2:
Input: nums = [0]
Output: [0]
Constraints:
1 <= nums.length <= 5000
0 <= nums[i] <= 5000
Complexity Analysis
- Time Complexity:
- Space Complexity:
905. Sort Array By Parity LeetCode Solution in C++
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& nums) {
int l = 0;
int r = nums.size() - 1;
while (l < r) {
if (nums[l] % 2 == 1 && nums[r] % 2 == 0)
swap(nums[l], nums[r]);
if (nums[l] % 2 == 0)
++l;
if (nums[r] % 2 == 1)
--r;
}
return nums;
}
};
/* code provided by PROGIEZ */
905. Sort Array By Parity LeetCode Solution in Java
class Solution {
public int[] sortArrayByParity(int[] nums) {
int l = 0;
int r = nums.length - 1;
while (l < r) {
if (nums[l] % 2 == 1 && nums[r] % 2 == 0) {
int temp = nums[l];
nums[l] = nums[r];
nums[r] = temp;
}
if (nums[l] % 2 == 0)
++l;
if (nums[r] % 2 == 1)
--r;
}
return nums;
}
}
// code provided by PROGIEZ
905. Sort Array By Parity LeetCode Solution in Python
class Solution:
def sortArrayByParity(self, nums: list[int]) -> list[int]:
l = 0
r = len(nums) - 1
while l < r:
if nums[l] % 2 == 1 and nums[r] % 2 == 0:
nums[l], nums[r] = nums[r], nums[l]
if nums[l] % 2 == 0:
l += 1
if nums[r] % 2 == 1:
r -= 1
return nums
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.