Evens First, Each Ascending

EasySorting & SearchingFree

Problem

A warehouse labels pallets with integer codes. For loading, all even codes go first, then all odd codes; inside each group the codes are in ascending order.

Given codes, return them in that loading order. Codes can be negative: parity is about the number itself, so -4 is even and -3 is odd.

Example 1

Input:
codes = [5, 2, 8, 1, 4]
Output:
[2, 4, 8, 1, 5]

Evens 2, 4, 8 in ascending order, then odds 1, 5.

Example 2

Input:
codes = [-3, -4, 0, 7]
Output:
[-4, 0, -3, 7]

Constraints

  • 0 ≤ codes.length ≤ 10^5
  • -10^9 ≤ codes[i] ≤ 10^9

Hint

Show the first hint

You are sorting by two criteria at once. Which one decides first?

Walkthrough

How to approach it

01Clarify before coding

  • Is zero even? Yes.
  • How is the parity of a negative number defined? Mathematically: -3 is odd, -4 is even.
  • Must equal codes keep any particular relative order? No, equal codes are indistinguishable.

02Brute force

Filter the evens, sort them; filter the odds, sort them; concatenate.

Cost: O(n log n) time and O(n) space. This is already optimal; the point of the problem is expressing the order as one sort key.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.