102. Aggregate Gift Card Data

Aggregate Gift Card Data
Design a system to manage payments using gift cards.

The system should support adding users with gift cards, making payments using one or more gift cards, and returning aggregated gift card data for a user.
A user can use multiple gift cards in a single payment.

Methods

Add User

void addUser(String userId, List<String> giftCards)
  • Adds a new user and the gift cards owned by that user.
  • Each item in giftCards is of the form "giftCardId,balance".
  • userId and Each giftCardId is non-blank, globally unique, and contain only characters from [a-z0-9].
  • If addUser() is called with an existing userId, ignore the call.

Add Payment

boolean addPayment(String userId, List<String> giftCardsUsed)
  • Deducts payment amounts from one or more gift cards of the given user.
  • Each item in giftCardsUsed is of the form "giftCardId,amountUsed".
  • Return false if:
    • userId is blank or does not exist,
    • any giftCardId does not belong to that user, or
    • any gift card does not have enough balance.
  • If the payment fails, no gift card balance should be changed.
  • Return true otherwise.

Aggregate Gift Card Data

List<String> aggregateGiftCardData(String userId)
  • Returns all gift cards owned by the user, sorted by current balance in descending order.
  • If two gift cards have the same balance, the lexicographically smaller giftCardId comes first.
  • Each returned row must be of the form "giftCardId,balance".
  • If the user does not exist or userId is blank, return an empty list.

Constraints

  • 1 ≤ userId.length() ≤ 50
  • 0 ≤ number of gift cards for a user ≤ 100
  • 1 ≤ giftCardId.length() ≤ 50
  • 0 ≤ balance ≤ 1000000
  • 0 ≤ amountUsed ≤ 1000000
  • Each gift card belongs to exactly one user.

Examples

Example 1

addUser(userId = "u1", giftCards = ["gc1,100", "gc2,40", "gc3,100"])
  • No return value
addPayment(userId = "u1", giftCardsUsed = ["gc1,25", "gc2,10"])
  • true
aggregateGiftCardData(userId = "u1")
  • ["gc3,100", "gc1,75", "gc2,30"]

Example 2

addUser(userId = "u2", giftCards = ["gc5,20"])
  • No return value
addPayment(userId = "u2", giftCardsUsed = ["gc5,25"])
  • false
aggregateGiftCardData(userId = "u2")
  • ["gc5,20"]

Example 3

addPayment(userId = "u9", giftCardsUsed = ["gc1,10"])
  • false
aggregateGiftCardData(userId = "u9")
  • []

Example 4

addUser(userId = "u3", giftCards = [])
  • No return value
aggregateGiftCardData(userId = "u3")
  • []




Please use Laptop/Desktop or any other large screen to add/edit code.