Maximized Parity Sequence — Problem Statement & Solution Guide
Problem Description
Given an integer array nums of length N, reorder its elements to produce a sequence that is lexicographically maximal while satisfying the following rule: every even number must appear before any odd number. Within the group of even numbers and within the group of odd numbers you may arrange the elements arbitrarily. To achieve the maximal lexicographic order, place the even numbers in descending order followed by the odd numbers also in descending order. Return the resulting reordered array.
DSA Pattern Breakdown
DSA Pattern Breakdown
"Maximized Parity Sequence"
WHY DOES IT MATTER?
This pattern is essential for problems involving constrained ordering where a global partition rule (like parity, priority, or status) must be respected while optimizing a secondary metric (like value or time) within each partition. It tests the ability to decompose a complex global constraint into independent local optimizations.
OPTIMIZATION CHALLENGE
The key insight is that the global lexicographic maximum is achieved by independently maximizing the lexicographic order of each partition. This avoids the need for complex global sorting with custom comparators that might be error-prone or less efficient. It reduces the problem to two independent sorting tasks.
REAL-WORLD CONNECTION
This is analogous to task scheduling in operating systems or cloud computing, where high-priority tasks (even) must be executed before low-priority tasks (odd), and within each priority level, tasks are scheduled in a specific order (e.g., shortest job first or highest reward first) to maximize system throughput or user satisfaction.
In an interview, explicitly state that you are treating the even and odd groups as independent subproblems. This demonstrates a strong understanding of divide-and-conquer principles and modular thinking. Also, mention that if the input is already partially sorted, you could use stable partitioning to maintain relative order, but since we need descending order, a full sort is typically required unless the input has specific properties.
COMPLEXITY AT A GLANCE
O(N log N)O(N)Core Theory — Why This Approach?
The problem 'Maximized Parity Sequence' is a classic application of stable partitioning combined with custom sorting. The core constraint is that all even numbers must precede all odd numbers. To maximize the lexicographic order of the resulting sequence, we must independently maximize the order within the even group and the odd group. Since lexicographic comparison prioritizes earlier elements, the largest possible even number must be placed at the very beginning, followed by the next largest even number, and so on. Once the even numbers are exhausted, the largest odd number must follow, followed by the next largest odd number. This implies that both the even and odd subsets must be sorted in descending order.
Interview Questions on This Problem
Q1At a fintech platform like Stripe, how would you optimize the ordering of transaction logs where high-priority (even ID) transactions must appear before low-priority (odd ID) transactions, while maintaining the highest possible timestamp order within each priority class?
You would partition the logs into two streams based on ID parity. Then, sort each stream in descending order of timestamp (or ID, if timestamp is not the primary sort key). Finally, concatenate the high-priority stream followed by the low-priority stream. This ensures the strict priority constraint is met while maximizing the lexicographic (or chronological) order within each group.
Q2In a high-growth startup's recommendation engine, if you need to display 'Premium' (even) items before 'Standard' (odd) items, and within each category, you want the most popular items first, how do you handle this efficiently in a streaming context?
Maintain two priority queues (max-heaps) or sorted lists. As items arrive, insert them into the appropriate heap based on their ID parity. When generating the response, drain the 'Premium' heap first, then the 'Standard' heap. This ensures O(log N) insertion and O(N log N) total ordering if sorting is required, or O(N) if the heaps are already maintained in order.
Q3At a global product company like Amazon, if you are designing a search result page where 'In-Stock' (even) products must appear before 'Out-of-Stock' (odd) products, and within each group, products are ranked by relevance score (descending), how do you ensure this is done in O(N log N) time?
Filter the product list into two arrays: one for in-stock and one for out-of-stock. Sort both arrays in descending order of relevance score. Concatenate the in-stock array followed by the out-of-stock array. This approach leverages standard sorting algorithms and ensures the global constraint is satisfied while optimizing local ordering.
Examples
Input
[3, 1, 2, 4, 7, 6]
Output
[6, 4, 2, 7, 3, 1]
Explanation: Even numbers are {2,4,6}. Sorting them descending gives [6,4,2]. Odd numbers are {3,1,7}. Sorting them descending gives [7,3,1]. Concatenating the two groups yields the lexicographically largest valid sequence: [6,4,2,7,3,1].
Input
[0, -5, -2, 9, 8]
Output
[8, 0, -2, 9, -5]
Explanation: Even numbers: {0,-2,8} → descending order [8,0,-2]. Odd numbers: {-5,9} → descending order [9,-5]. The final sequence is the even block followed by the odd block: [8,0,-2,9,-5].
Input
[11]
Output
[11]
Explanation: The array contains only an odd element, so the rule imposes no restriction. The single element itself is the maximal sequence.
Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- All operations must run in O(N log N) time or better
- Only O(1) additional space beyond the output array is allowed
Optimal Approach & Strategy
Partition the array into two lists: one for even numbers and one for odd numbers. Sort both lists in descending order and concatenate the even list followed by the odd list. This ensures the parity constraint is met and the lexicographic order is maximized within each group.
Brute Force Approach
Generate all possible permutations of the array, filter out those that violate the parity constraint (even before odd), and select the lexicographically largest valid permutation. This approach is computationally infeasible for large N due to factorial time complexity.
Verified Code Solutions
function solution(nums) {
let sum = 0;
for (let num of nums) {
sum += num;
}
return sum;
}class Solution {
public:
int solution(vector<int>& nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
};class Solution {
public int solution(int[] nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
}def solution(nums):
return sum(nums)function solution(nums) {
let sum = 0;
for (let num of nums) {
sum += num;
}
return sum;
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.