Magicsheet logo

Number of Ways to Buy Pens and Pencils

Medium
88.6%
Updated 6/1/2025

Asked by 1 Company

Number of Ways to Buy Pens and Pencils

What is this problem about?

The Number of Ways to Buy Pens and Pencils problem gives you a total budget and the costs of pens and pencils (cost1 and cost2). Count the number of ways to spend some or all of the budget on pens and pencils (you can buy 0 or more of each). This easy math problem uses integer division enumeration.

Why is this asked in interviews?

Reddit asks this to test simple enumeration within a mathematical budget constraint. The key insight: fix the number of pens from 0 to budget/cost1, then for each pen count, compute how many pencils can be bought with the remaining budget. The math and enumeration interview pattern is applied concisely.

Algorithmic pattern used

Enumerate pen count + floor division for pencils. For pens = 0, 1, 2, ..., budget // cost1: remaining = budget - pens * cost1. Pencils = 0 to remaining // cost2. That's remaining // cost2 + 1 valid pencil counts (including 0). Sum all pencil counts across all pen counts.

Example explanation

budget=10, cost1=4, cost2=3.

  • pens=0: remaining=10. Pencils 0..3 → 4 ways.
  • pens=1: remaining=6. Pencils 0..2 → 3 ways.
  • pens=2: remaining=2. Pencils 0..0 → 1 way.
  • pens=3: 3*4=12>10. Stop. Total = 4+3+1 = 8.

Common mistakes candidates make

  • Not including 0 pens or 0 pencils (buying nothing is allowed).
  • Using floating-point division instead of integer floor division.
  • Off-by-one: remaining // cost2 + 1 valid counts (0 through max), not just remaining // cost2.
  • Not iterating up to budget // cost1 (inclusive).

Interview preparation tip

Two-variable budget problems enumerate one variable and compute the other with floor division. This O(budget/cost1) approach is efficient for reasonable inputs. The +1 in the pencil count formula accounts for buying 0 pencils. Practice similar "count ordered pairs (a,b) where cost1a + cost2b ≤ budget" — they follow the same enumeration pattern. The key skill is recognizing floor division as the tool for "how many fit within remaining budget."

Similar Questions