Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Card Affordability Check
00:00
5 left

Card Affordability Check

EasyPython

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):
Interviewer

Your question is Card Affordability Check. Start with the requirements in the Question tab.

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.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.