Skip to the code
+25 XP

#88 Secret Gift Exchange

medium

A team app runs a gift exchange: everyone gives one gift and gets one, nobody draws themselves, and all gifts form one big circle. It uses a variant of Fisher-Yates called Sattolo's algorithm.

Start with order = [0, 1, ..., n - 1]. For i from n - 1 down to 1, take the next number r from randoms (in order), set j = Math.floor(r * i) (so j is always less than i), and swap order[i] and order[j]. Then person names[i] gives a gift to names[order[i]].

Write giftExchange(names, randoms) that returns an array where item i is the name of the person names[i] gives to.

Example 1

Input: names = ["Ana","Ben","Cy"], randoms = [0.5,0.9]
Output: ["Cy","Ana","Ben"]

i = 2: j = 1, so order is [0, 2, 1]. i = 1: j = 0, so order is [2, 0, 1]. Ana gives to Cy, Ben to Ana, Cy to Ben.

Example 2

Input: names = ["A","B"], randoms = [0.3]
Output: ["B","A"]

With two people, they must swap gifts.

Constraints

  • 2 <= names.length <= 10^5
  • randoms.length === names.length - 1
  • 0 <= randoms[i] < 1
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).