Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Card Affordability Check

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Card Affordability Check. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

In a Brex rewards game simulation, each card has a color-specific gem cost. A player may pay a cost with gems of the same color or use wild gems to cover any remaining shortage. Write can_purchase() to determine whether the player can afford one card.

Use each gem at most once. Gems and costs are dictionaries mapping color names to nonnegative integers. The optional key "wild" represents gems that can substitute for any color. Missing color keys represent zero gems.

Formal Specification

Implement can_purchase(gems, cost):

  • gems: a dictionary from color strings to available gem counts.
  • cost: a dictionary from color strings to required gem counts.
  • Return True if all required colored gems can be paid using matching gems plus available wild gems.
  • Return False otherwise.
  • Extra colored or wild gems do not matter.

A greedy strategy is sufficient: use matching gems first, then count the total remaining shortage and compare it with the wild-gem count.

Constraints

  • 1 <= len(cost) <= 10^5
  • 0 <= len(gems) <= 10^5
  • 0 <= gems[color] <= 10^9
  • 0 <= cost[color] <= 10^9
  • Color names are nonempty strings
  • The key "wild" is reserved for wild gems

Function Signature

def can_purchase(gems, cost):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output