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.
nums?
nums will be a list of integers.With these clarifications, we can proceed to devise a strategy to implement the solution.
evens and odds.evens if it is even, or to odds if it is odd.evens and odds lists to form the desired output.i = 0) and one at the end (j = len(nums) - 1).Given the simplicity and clarity of the first approach, let’s start with that.
def sortArrayByParity(nums):
evens = []
odds = []
for num in nums:
if num % 2 == 0:
evens.append(num)
else:
odds.append(num)
return evens + odds
evens and odds lists.Now, let’s consider the in-place approach for completeness.
def sortArrayByParity(nums):
i, j = 0, len(nums) - 1
while i < j:
if nums[i] % 2 > nums[j] % 2:
nums[i], nums[j] = nums[j], nums[i]
if nums[i] % 2 == 0:
i += 1
if nums[j] % 2 == 1:
j -= 1
return nums
This provides a more memory-efficient solution while maintaining similar time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?