Distribute discount coupons evenly between new and old users

Question:

I recently got this problem in an interview. Suppose you have 3 types of coupon:

  1. Free Shipping( To be distributed to 10% users)
  2. By one Get One (To be distributes to 10% users)
  3. Flat 10% off (To be distributed to 80%)

The tasks is to find a way to distribute the coupons such that in every checkout the user is provided with a coupon and this coupon should one of above three. There are multiiple users coming in your system and this distribution pattern should be mainitained in the system.

I was not able to slove the problem. I think we need to assign a priority to every token and select them in random.

Asked By: Jinja2Django

||

Answers:

There are two major options: randomized approach and deterministic one.

Randomized approach would use a distribution function to decide which coupon to assign to a given user. The challenge is to make this function fair and meet 10/10/80 numbers.

A simple way to create a good distribution is to use hashing. For example, take user id (or something else unique about user, like email) and hash it using cryptographically strong hash function. The outcome will be a number, which is uniformly distributed across hash’s range. Now you can take first 10% of the range for the first coupon, second 10% of the range for the second coupon and the rest is the third coupon.

A completely different approach would be using a deterministic model. Since you have concurrent users coming to the system, you will need to synchronize the selection process somehow.

You could use a queue for coupons – add 10 of coupon #1, 10 of coupon #2 and 80 of coupon #3 to a list (or multiply the number by 10, 100, 1000). Shuffle the list and put it into a queue. Now, when a customer is at checkout, read the next coupon from the queue, which will be random from customer’s point of view. And have a job to refill the queue as needed.

There are many other approaches to handle the distribution, depending on the system scale, but queue is a simple one.

I would go with a randomized approach btw, as it requires less infrastructure.

Answered By: AndrewR