Interview Questions/Coding/One-Swap Previous Schedule

One-Swap Previous Schedule

Preview mode. Log in to edit, run, submit, and save progress.

Medium

One-Swap Previous Schedule

A scheduler stores a numeric ordering code as an array. The scheduler may perform at most one swap between two positions. Your task is to produce the largest possible ordering code that is still strictly smaller than the current ordering. If no single swap can make the code smaller, return the original code unchanged. Duplicate values must be handled carefully because swapping equal values does not change the code. Input Format: You are given an integer array codes. Output Format: Return the best previous ordering code obtainable with at most one swap.

Examples

Example 1
Input:
codes = [3, 2, 1]
Output:
3 1 2

Explanation: The first useful drop is at index 1, value 2. Swap it with 1 at index 2 to get [3, 1, 2], which is the previous one-swap schedule.

Approach hint

Look for the state that actually matters after each operation.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

solution.cpp