Solving Leetcode Interviews in Seconds with AI: Sort Array By Parity
Introduction
In this blog post, we will explore how to solve the LeetCode problem "905" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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
Explanation
Here's the solution to rearrange the array such that even numbers come before odd numbers:
- Two-Pointer Approach: Use two pointers,
leftandright, initialized at the beginning and end of the array, respectively. - Move Pointers: Move the
leftpointer to the right until it points to an odd number and move therightpointer to the left until it points to an even number. Swap: If
leftis less thanright, swap the elements at these pointers. Repeat untilleftandrightcross each other.Time Complexity: O(n), Space Complexity: O(1)
Code
def sort_array_by_parity(nums: list[int]) -> list[int]:
"""
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
"""
left, right = 0, len(nums) - 1
while left < right:
if nums[left] % 2 == 0:
left += 1
elif nums[right] % 2 != 0:
right -= 1
else:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
return nums