Start learning free

LESSON 55 OF 348 · CALCULATIONS - CHALLENGES

Buy Candy in TypeScript: Floor Division and Extra Cost

Practice Read the full explanation

A box of candy costs price dollars. You have balance dollars. Compute the number of boxes of candy you can buy and return how many more dollars you need to buy one more box of candy.

Example:

Input: price = 4, balance = 9

Output: 3

Explanation:
You can buy two boxes of candy that costs 4 * 2 = 8 dollars.
If you would have 12 dollars you could buy 3 boxes (one more), so you would need 3 more dollars.
Hints:

The number of boxes we can buy is the integer part of the division of balance by price. Let's store this number in a variable boxes.

We want to buy one more box, so a total of boxes + 1 boxes, which require (boxes + 1) * price dollars. Let's store this product into another variable balanceNeeded.

Finally the answer is the difference between balanceNeeded and balance.
STEP 1 OF 4
    Ctrl + Enter to check

    TYPESCRIPT · CALCULATIONS - CHALLENGES

    Buy Candy in TypeScript, explained

    Problem overview

    A box of candy costs price dollars and you have balance dollars. The method buyCandy must return how many more dollars you would need to buy one more box than you can buy now.

    Take price = 4 and balance = 9. You can buy two boxes, which cost 8 dollars. To afford a third box you would need 12 dollars in total, and you have 9, so you are 3 dollars short. The answer is 3.

    Approach

    The question has three parts, and each becomes one small calculation:

    1. How many whole boxes can you buy now?
    2. What is the total cost of one more box than that?
    3. How much of that total do you not have?

    Splitting the work this way keeps each line simple and gives every value a name that says what it means.

    Step by step

    Step 1: the number of boxes

    You can buy balance / price boxes, but only whole ones. In TypeScript, / always does decimal division, so 9 / 4 is 2.25, not 2. There is no separate integer division. To keep the whole part, wrap the quotient in Math.floor, which rounds down. That gives boxes.

    For positive numbers, Math.trunc would give the same result. The two differ only for negative values: Math.floor(-9 / 4) is -3, while Math.trunc(-9 / 4) is -2. Here both inputs are positive, so either works.

    Step 2: the cost of one more box

    One more than boxes is boxes + 1, and each box costs price, so the total is (boxes + 1) * price. The parentheses matter: without them, only the 1 would be multiplied by price. Store the total in balanceNeeded.

    Step 3: the missing money

    The gap between what you need and what you have is balanceNeeded - balance. Store it in extraBalance.

    Step 4: return it

    Return extraBalance. The method is meant to give the answer back, not to print it.

    The solution in TypeScript

    class Solution {
        buyCandy(price: number, balance: number): number {
            const boxes: number = Math.floor(balance / price);
            const balanceNeeded: number = (boxes + 1) * price;
            const extraBalance: number = balanceNeeded - balance;
            return extraBalance;
        }
    }
    

    Tracing the example with price = 4 and balance = 9: boxes is Math.floor(2.25), which is 2. Then balanceNeeded is 3 * 4 = 12, and extraBalance is 12 - 9 = 3.

    Language details

    • Division does not truncate. Without Math.floor, boxes would be 2.25, and the final result would be wrong. The type number covers both integers and decimals, so the compiler can't warn you.
    • Annotations are optional here. TypeScript infers number for all three constants. They are written out to make the types explicit, and they are erased when the code is compiled.
    • Use const. None of the three values changes after it is set.

    You can see the effect of skipping the rounding with the example. Without it, boxes would be 2.25, the total would be (2.25 + 1) * 4 = 13, and the result would be 4 instead of 3. A fractional number of boxes gives a price that nobody can actually pay.

    Complexity

    The method does a fixed number of arithmetic operations whatever the input values are, so it runs in O(1) time and uses O(1) extra space.

    Edge cases and common mistakes

    • An exact multiple. With price = 4 and balance = 8, you can buy 2 boxes with nothing left over, and the answer is 4, a full price, not 0. The formula gives this correctly: (2 + 1) * 4 - 8 = 4.
    • Not enough for any box. With price = 5 and balance = 3, boxes is 0, so the answer is 5 - 3 = 2.
    • Zero balance. With balance = 0, the answer is exactly price.
    • Forgetting to round down. Using balance / price directly gives a fraction and a wrong total.
    • Missing parentheses. boxes + 1 * price multiplies first, giving the wrong amount.
    • Returning the cost instead of the gap. The answer is how much more you need, not the total balanceNeeded.

    Testing

    pricebalanceresult
    493
    484
    404
    532
    431
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free