Build Array from Permutation
Real-world version: Follow Each Card TwiceThe statement here is our own: the same inputs, outputs and technique.
A rack has pigeonhole slots numbered 0 to n - 1. Slot i holds a card reading cards[i], which is the number of a slot on the same rack and may be the number of slot i itself. Every slot number appears on exactly one card, so the cards are a rearrangement of the slot numbers.
Fill a second rack of the same size. For each slot i, read the card in slot i of the original rack, go to the slot whose number it gives, and copy the number written on the card there into slot i of the new rack.
Both lookups read the original rack, never the rack being filled. Return the contents of the new rack, in slot order.
Examples
Example 1
- Input
- cards = [5, 3, 1, 4, 0, 2]
- Output
- [2, 4, 3, 0, 5, 1]
For slot 1 the card reads 3, and the card in slot 3 reads 4, so slot 1 of the new rack holds 4. For slot 4 the card reads 0, and the card in slot 0 reads 5, so slot 4 of the new rack holds 5.
Example 2
- Input
- cards = [3, 0, 4, 1, 2]
- Output
- [1, 3, 2, 0, 4]
For slot 0 the card reads 3 and the card in slot 3 reads 1, so the new rack starts with 1. For slot 2 the card reads 4 and the card in slot 4 reads 2.
Example 3
- Input
- cards = [2, 1, 0]
- Output
- [0, 1, 2]
Slot 0 points at slot 2, whose card reads 0. Slot 1 points at itself. Slot 2 points at slot 0, whose card reads 2.
Constraints
- 1 <= cards.length <= 1000
- 0 <= cards[i] < cards.length
- The numbers in cards are all different.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def follow_twice(cards: list[int]) -> list[int]:public int[] followTwice(int[] cards)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Concatenation of ArrayReal-world version: Two Cycle PlayoutEasy
- Reshape the MatrixReal-world version: Relaying the Contact SheetEasy
- Separate the Digits in an ArrayReal-world version: Digit Cells for the Ticket CodesEasy
- Distribute Elements Into Two Arrays IReal-world version: Splitting Parcels Onto Two Intake TraysEasy