Problems/Sort and Search/Sort Array
Sort and Search
medium

Sort Array

Rearrange the elements of an array of integers such that all even numbers come before all odd numbers. This problem tests understanding of array manipulation and sorting concepts.

arraytwo-pointersin-placesortingpartitioning

Problem Statement

Given an array of integers, rearrange the array in-place such that all even numbers appear at the beginning of the array, followed by all odd numbers. The relative order of even numbers and odd numbers does not matter.

Example 1
Input: [3, 1, 2, 4, 5, 6]
Output: [2, 4, 6, 3, 1, 5]
The even numbers (2, 4, 6) are moved to the front, and the odd numbers (3, 1, 5) are moved to the back. The order within each group is maintained.
Example 2
Input: [7, 9, 1, 3, 5]
Output: [7, 9, 1, 3, 5]
Since all numbers are odd, the array remains unchanged as it already satisfies the condition.
Constraints
  • -1 <= length of nums <= 10^5
  • --10^9 <= nums[i] <= 10^9
  • -The array contains only integers.
  • -The solution must be in-place (no extra space beyond O(1)).

Brute Force Approach

Imagine you have a deck of cards and need to separate the red cards from the black cards. A brute-force approach would be to create two new decks, one for red and one for black, going through the original deck one card at a time. This requires extra space proportional to the input size and takes linear time to iterate through the array.

TimeO(n)
SpaceO(n)

Ready to practice?

Work through this problem with AI coaching and get real-time feedback

Practice This Problem