Rearrange Seats by Rating — Problem Statement & Solution Guide

ArraysMediumpattern sorting by custom criteria
TimeO(n log n) (or O(n) expected with QuickSelect)
|
SpaceO(1) additional

Quick Answer & Algorithm Key Takeaway

Master coding challenges related to Arrays and solve the Rearrange Seats by Rating problem optimally.

TopicArrays
Patternpattern sorting by custom criteria
TimeO(n log n) (or O(n) expected with QuickSelect)
SpaceO(1) additional

Problem Description

Given an integer array nums representing seat ratings, reorder the elements so that every rating placed at an odd index (0‑based) is strictly greater than any rating placed at an even index. If the array length is odd, the element at the central index must be the maximum rating overall. Return any arrangement that satisfies these rules.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Rearrange Seats by Rating"

medium

WHY DOES IT MATTER?

This pattern captures a class of problems where a global ranking must be split into two interleaved groups (high vs. low). Mastering it teaches you how to turn relational constraints into a simple partition, a skill that recurs in load‑balancing, cache tiering, and priority scheduling.

OPTIMIZATION CHALLENGE

The insight is that you do not need a full ordering of every element; you only need to know which half belongs to the "high" group. Selecting the cutoff value with QuickSelect reduces the problem from O(n log n) sorting to O(n) linear time.

REAL-WORLD CONNECTION

Think of a server farm where high‑priority requests are routed to fast nodes (odd slots) and low‑priority ones to slower nodes (even slots). Ensuring every fast node handles a request with higher priority than any slow node mirrors the odd‑greater‑than‑even requirement.

During an interview, first state the partition view, then mention sorting for simplicity, and finally propose QuickSelect for optimality. This shows both correctness and depth of algorithmic knowledge.

COMPLEXITY AT A GLANCE

⏱ Time:O(n log n) (or O(n) expected with QuickSelect)
💾 Space:O(1) additional

Core Theory — Why This Approach?

The problem asks for a permutation of the input array such that every element at an odd index is strictly greater than every element at an even index, and when the length is odd the middle element must be the global maximum. A naive solution would try all permutations, which is factorial in time and impossible for any realistic n. The key observation is that the ordering constraints only care about a global partition between two groups – the "high" values that will occupy odd positions and the "low" values that will occupy even positions. By sorting the array we obtain a total order; the largest ⌈n/2⌉ elements can be placed at odd indices (and the very largest at the centre when n is odd) while the remaining floor(n/2) smallest elements fill the even slots. This yields a valid arrangement in O(n log n) time. More advanced linear‑time solutions use the QuickSelect algorithm to find the median‑like pivot that separates the top ⌈n/2⌉ values, then a single pass to interleave them, achieving O(n) expected time and O(1) extra space.

Interview Questions on This Problem

Q1How would you rearrange an array so that all elements at odd indices are greater than all elements at even indices in O(n log n) time?

Sort the array, then fill odd positions with the largest ⌈n/2⌉ elements (starting from the end of the sorted list) and fill even positions with the remaining smallest elements. If n is odd, place the maximum element at the middle index.

Q2Can you achieve the same ordering in linear time? What technique would you use?

Yes. Use QuickSelect (or the median‑of‑medians deterministic selection) to find the kth largest element where k = ⌈n/2⌉. Partition the array around that pivot, then interleave the two partitions: the higher partition goes to odd indices, the lower to even indices. This runs in O(n) expected time and O(1) extra space.

Q3Why does the requirement that the central element be the global maximum only matter when the array length is odd, and how does your algorithm guarantee it?

When n is odd there is a unique middle index that is both even and odd in the alternating pattern. Placing the maximum there ensures the "odd‑greater‑than‑even" rule still holds because the maximum is larger than every other element. In the sorting‑based construction the maximum naturally ends up at the end of the sorted list and is assigned to the middle odd position, satisfying the rule automatically.

Examples

Example 1

Input

[10,1,7,3,5,2]

Output

[3,10,2,7,1,5]

Explanation: Sorted descending → [10,7,5,3,2,1]. Length is even, so no central slot. Fill odd positions 1,3,5 with the three largest values 10,7,5. Remaining values 3,2,1 go to even positions 0,2,4, yielding [3,10,2,7,1,5]. All odd‑index values (10,7,5) exceed every even‑index value (3,2,1).

Example 2

Input

[8,6,4,2,9]

Output

[4,8,9,6,2]

Explanation: Sorted descending → [9,8,6,4,2]. Length is odd, so place the maximum 9 at middle index 2. Next two largest (8,6) occupy odd indices 1 and 3. Remaining (4,2) fill even indices 0 and 4, giving [4,8,9,6,2]. Odd‑index values (8,6) are larger than all even‑index values (4,2) and the middle element is the overall maximum.

Example 3

Input

[15]

Output

[15]

Explanation: Single element array already satisfies the condition; the sole element is both the middle and the maximum.

Constraints

  • 1 <= nums.length <= 100000
  • -10^9 <= nums[i] <= 10^9
  • Algorithm must run in O(n log n) time or better
  • Only O(1) extra space besides the output array is allowed

Optimal Approach & Strategy

Sort the array and interleave the two halves, or use QuickSelect to partition and then interleave, achieving linear or n log n time with constant extra space.

Brute Force Approach

Generate every permutation and test the condition – exponential time and infeasible for large n.

Code Solutions

JavaScript Solution
Time: O(n log n) (or O(n) expected with QuickSelect)
// Rearrange so that every odd index holds a value greater than any even index.
// If length is odd, the middle element becomes the global maximum.
function rearrangeSeats(nums) {
    if (!nums || nums.length === 0) return [];
    nums.sort((a, b) => a - b); // ascending
    const n = nums.length;
    const res = new Array(n);
    let lo = 0, hi = n - 1;
    for (let i = 0; i < n; ++i) {
        if (i % 2 === 0) {
            res[i] = nums[lo++]; // smallest to even positions
        } else {
            res[i] = nums[hi--]; // largest to odd positions
        }
    }
    return res;
}

// Example driver (can be removed in production)
if (require.main === module) {
    const fs = require('fs');
    const input = fs.readFileSync(0, 'utf8').trim().split(/\s+/).map(Number);
    const n = input[0] || 0;
    const arr = input.slice(1, 1 + n);
    console.log(rearrangeSeats(arr).join(' '));
}

Asked in Top Tech Interviews

Infosys

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.