All problems
0680EasyArraySimulation

Follow Each Card Twice

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1920Build Array from Permutation

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def follow_twice(cards: list[int]) -> list[int]:
Java
public int[] followTwice(int[] cards)
September 7
Apply