Bag of Tokens solution explained

Bag of Tokens is a sorted two-pointer greedy: spend power (energy) on the cheapest unused token to gain a point whenever you can, and when you cannot, trade one point for the most expensive unused token's value, then keep going. Return the highest score reached along the way rather than trusting the final one. Sorting makes it O(n log n) time.

By Published 8 min read

The problem in plain words

You hold a bag of tokens, each stamped with a number, and you start with a certain amount of energy and a score of 0. You can use each token at most once, in any order, in one of two ways. Spend it: pay energy equal to its number and gain one point, if you have enough energy. Cash it in: give up one point and gain energy equal to its number, if your score is at least 1. You can also stop at any time or leave tokens unused. What is the largest score you can reach?

Small examples, written for this page
TokensStarting energyBest scoreNote
[30, 10, 60, 20]252Spend 10, cash in 60, spend 20 and 30
[50]100Cannot afford the only token
[5, 5, 5]203Enough energy to spend every token
[40, 15]100No point to trade, so nothing can start
[]70An empty bag
Small examples, written for this page. Scroll sideways on a small screen.

Before coding, confirm that the answer is the best score at any moment rather than the score after using every token, that order is free, and that leaving tokens unplayed is allowed. All three are true in the standard version, and each one affects the code.

What the interviewer is checking

There is very little code here, so the round is about reasoning. Can you spot that the two moves want opposite tokens? Can you explain why a trade that lowers your score for a moment can raise the final answer? And do you notice that a careless simulation can let the score fall at the very end, so the safest return value is a running maximum? Candidates who simulate greedily but return the last score are a classic near-miss.

Slow approach: search every sequence of moves

Without any insight you can explore every order and every choice. A state is the set of used tokens, the current energy and the current score. From each state, try spending or cashing in each unused token where the move is legal, and keep the best score seen. Caching states helps, but the number of states still grows exponentially with the number of tokens, so this only works for a handful of them. It is useful as a reference to check a faster idea on small inputs.

from functools import lru_cache

def token_score_slow(tokens, energy):
    n = len(tokens)

    @lru_cache(maxsize=None)
    def explore(used, energy, score):
        top = score
        for i in range(n):
            if used >> i & 1:
                continue
            if energy >= tokens[i]:
                top = max(top, explore(used | 1 << i, energy - tokens[i], score + 1))
            if score >= 1:
                top = max(top, explore(used | 1 << i, energy + tokens[i], score - 1))
        return top

    return explore(0, energy, 0)
Python, exponential: depth-first search with a cache.

The two insights

  • Spend the cheapest token. Every spend gains exactly one point no matter which token you use, so using the smallest one leaves the most energy behind and the larger tokens available for later.
  • Cash in the most expensive token. Every cash-in costs exactly one point, so it should return as much energy as possible. The largest unused token does that.

Put together, sort the tokens and work from both ends. The left pointer is the next token to spend, and the right pointer is the next token to cash in. Prefer spending, because it raises the score. Only when you cannot afford the cheapest token, and you have a point to give and at least one other token left to spend it on, do you cash in from the right. If neither move is possible, stop.

Why require two tokens left? If the left and right pointers meet on one token, cashing it in costs a point and leaves nothing to spend the new energy on, so it can only lower the score. The running maximum would protect the answer anyway, but stopping is cleaner and easier to explain.

Main approach: sorted tokens, two pointers, running best

def token_score(tokens, energy):
    bag = sorted(tokens)
    lo, hi = 0, len(bag) - 1
    score = best = 0
    while lo <= hi:
        if energy >= bag[lo]:  # spend the cheapest token for a point
            energy -= bag[lo]
            lo += 1
            score += 1
            best = max(best, score)
        elif score > 0 and lo < hi:  # cash in the priciest token for energy
            energy += bag[hi]
            hi -= 1
            score -= 1
        else:
            break
    return best
Python: O(n log n) time for the sort, O(n) for the copy.
function tokenScore(tokens, energy) {
  const bag = [...tokens].sort((a, b) => a - b);
  let lo = 0, hi = bag.length - 1, score = 0, best = 0;
  while (lo <= hi) {
    if (energy >= bag[lo]) {
      energy -= bag[lo++];
      best = Math.max(best, ++score);
    } else if (score > 0 && lo < hi) {
      energy += bag[hi--];
      score--;
    } else {
      break;
    }
  }
  return best;
}
JavaScript: the same loop, with a numeric sort.

Trace of the first example

Tokens [30, 10, 60, 20] sort to [10, 20, 30, 60], and energy starts at 25. Spend 10: energy 15, score 1, best 1. The next token costs 20 and energy is only 15, so cash in 60: energy 75, score 0. Spend 20: energy 55, score 1. Spend 30: energy 25, score 2, best 2. The pointers have crossed, so the answer is 2. Notice the dip to a score of 0 in the middle; the trade paid for two later points.

Complexity

Comparing the two methods
MethodTimeExtra space
Search over states with a cacheExponential in the token countExponential cache
Sort plus two pointersO(n log n)O(n) for the sorted copy
Comparing the two methods. Scroll sideways on a small screen.

After sorting, each token is touched at most once by either pointer, so the loop itself is linear. If token values are small integers, a counting sort would remove the log factor, but that is rarely asked.

Edge cases to test

  • An empty bag: the answer is 0.
  • Starting energy below every token: nothing can be spent, and with no points nothing can be cashed in, so 0.
  • Starting energy that covers every token: the answer is the number of tokens.
  • A single token you can afford: score 1.
  • Tokens [5, 40] with 5 energy: spend 5 for a point, then stop. A version without the two-token guard cashes in 40 and ends at 0, although 1 was reached.
  • Equal token values, which do not need special handling.

Mistakes that cost points

  • Returning the score at the end of the loop instead of the best score seen.
  • Cashing in the cheapest token or spending the most expensive, the reverse of what each move wants.
  • Cashing in when only one token is left, which drops the score for nothing.
  • Forgetting the else branch, so the loop spins forever when neither move is possible.
  • Trying a DP over energy values, which can be huge. The greedy needs no table.
  • In JavaScript, sorting without a comparator, so values compare as strings.

How to explain it out loud

Fictional example

Explaining the two moves to an interviewer
Candidate
Both moves change the score by exactly one, so the only question is which token to use. To gain a point, the cheapest token costs the least energy. To gain energy, the most expensive token gives the most.
Candidate
So I sort and use two pointers: spend from the left when I can, cash in from the right when I am stuck and still have a point and another token to use it on.
Candidate
The score can drop near the end, so I return the highest score I reached. Sorting costs O(n log n), and the loop is linear.

Other problems in this set

Assign Cookies is a gentler sorted greedy where both lists are sorted and matched from the small end. For the same inward-moving pointers with a weight limit instead of an energy budget, go back to Boats to Save People. The algorithm interview questions page lists other greedy and two-pointer patterns worth drilling.

Practice it with Natively

For a problem with a sneaky return value like this one, a recording of how you explained it is useful. Natively transcribes mock interviews on your computer, so you can reread whether you mentioned the running maximum. In practice it can also read the statement from a screenshot and suggest a strategy, which works best as something to compare with your own plan after an honest first attempt. More about an AI interview assistant on Mac and Windows.

Questions people ask

How do you solve Bag of Tokens?

Sort the tokens. Spend the cheapest unused token for a point whenever your power allows; when it does not, and you have a point and at least two tokens left, trade a point for the largest unused token. Return the highest score you reached.

Why use the smallest token to gain a point and the largest to gain power?

Both moves change the score by exactly one. Gaining a point should cost as little power as possible, and giving up a point should return as much power as possible.

Why return the maximum score instead of the final score?

A trade lowers the score for a moment, and a careless loop can end on such a trade. Tracking the best score seen keeps the answer correct either way.

What is the time complexity of Bag of Tokens?

O(n log n) for the sort. After sorting, each token is used at most once by one of the two pointers, so the loop is linear.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP