KatInterview

Till Payout: Greedy Bills and Coins, Listed A to Z

Greedy & IntervalsAuto-graded · 25 test cases
EasyAuto-gradedGreedy & Intervalsgreedystringsparsing

Last updated

Parse decimal money strings exactly into cents, detect underpayment or exact payment, then greedily break the change into named bills and coins and output them sorted alphabetically.

Till Payout

A shop's till receives two amounts written as decimal strings: the amount_due for a purchase and the amount_paid handed over by the customer. You must work out which bills and coins the cashier should hand back.

To avoid floating-point rounding errors, do all money arithmetic with integers (for example, by converting each amount to a whole number of cents).

Available denominations

NameValue in cents
PENNY1
NICKEL5
DIME10
QUARTER25
HALF DOLLAR50
ONE100
TWO200
FIVE500
TEN1000
TWENTY2000
FIFTY5000
ONE HUNDRED10000

Names containing a space (HALF DOLLAR, ONE HUNDRED) are single names; the space is part of the name.

Task

Implement a function that takes amount_due and amount_paid and returns a string:

  1. If amount_paid is less than amount_due, return "ERROR".
  2. If the two amounts are equal, return "ZERO".
  3. Otherwise, the change is amount_paid - amount_due. Build it greedily: repeatedly take the largest denomination that does not exceed what is still owed, until nothing remains. Return the names of all items handed back, in alphabetical (lexicographic) order, separated by commas with no extra spaces. A denomination used several times appears that many times.

Input format

Each argument is a string holding a non-negative decimal number with at most two digits after the decimal point. It may have no decimal point at all ("20"), a single fractional digit ("0.5" means 50 cents), or two fractional digits ("15.94").

Output format

One string: "ERROR", "ZERO", or the comma-separated, alphabetically sorted list of denomination names.

Constraints

  • 0.00 <= amount_due, amount_paid <= 10000.00
  • Each input consists only of digits and at most one decimal point.
  • At most two digits follow the decimal point.
  • Sorting is plain string ordering on the names (so, for example, ONE comes before ONE HUNDRED).

Examples

Example 1

Input: make_change('15.94', '16.00')

Output: 'NICKEL,PENNY'

Example 2

Input: make_change('1.02', '1.24')

Output: 'DIME,DIME,PENNY,PENNY'

Example 3

Input: make_change('50.00', '40.00')

Output: 'ERROR'

Hints

Hint 1

Do not use float. Split each string at the decimal point, multiply the whole part by 100, and add the fractional part padded on the right to exactly two digits (so "0.5" is 50 cents, not 5).

Hint 2

Check for underpayment and exact payment after converting to cents, before doing any breakdown.

Hint 3

Go through the denominations from largest to smallest and use divmod to get how many of each fit; then sort the collected names only at the end, since dispensing order and output order differ.