Social feed~15 min2s · 256 MBtarget O(n) time, O(n) spacegreedy
You work on a social feed. A feed page shows n posts, numbered 1 to n in their current order. Before it refreshes, the app reshuffles the page. Exactly fixed posts must stay at their position, and every other post must move to a different position.
Your team lead asks: "Which reshuffle should we use?" Many reshuffles can work, so the team picks the smallest one in dictionary order. Compare two lists from the first position: the smaller number at the first difference wins. The page can show up to 100,000 posts.
Write smallest_reshuffle(n, fixed).
n that holds each of the numbers 1 to n once. Position i (counting from 1) holds the post shown there after the shuffle.fixed positions i must hold the number i. In every other position, the number must differ from the position.Input: n = 5, fixed = 2
Output: [1, 2, 4, 5, 3]Keep the first 2 posts in place, as they give the smallest start. The other three must all move. The smallest list for them is 4, 5, 3.
| Position | Post | Result |
|---|---|---|
| 1 | 1 | kept |
| 2 | 2 | kept |
| 3 | 4 | moved |
| 4 | 5 | moved |
| 5 | 3 | moved |
Input: n = 4, fixed = 0
Output: [2, 1, 4, 3]No post may stay. The smallest list swaps neighbours.
Input: n = 3, fixed = 2
Output: []Two posts stay, so one post must move. A single post has nowhere to go, because every other position is taken by a post that stays. No list exists.
1 ≤ n ≤ 100,0000 ≤ fixed ≤ nYou cannot list the permutations: even 20 posts have 2,432,902,008,176,640,000 of them, and 100,000 posts have unimaginably more. The answer must be built directly, in one pass over the positions, with a rule for each choice.