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
ExperiencesCoaching
New
Practice
Mock InterviewsTimed interview simulations with feedbackSuccess 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
Start free
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

Whenever you're ready, walk me through your approach or go straight to the code. The requirements are in the Question tab.

Sign up free to run or submit. Log in
Code
Sign up free to run your code. Your draft is saved.Run with a free accountLog inLn 2
Run your code to see test output here.