Skip to content
Problem 306 · LeetCode 306(opens in a new tab)

Additive Number

MediumBacktracking

You get a string num made only of digits. Decide whether it can be cut into a list of at least three numbers where every number from the third on is the sum of the two just before it.

A number in the list may not start with 0 unless it is exactly 0, so "02" is never a valid piece. Return true if such a cut exists, false otherwise.

Example 1

Input:  num = "54954103"
Output: true
Why:    5, 49, 54, 103: 5 + 49 = 54 and 49 + 54 = 103
2 more examples and the constraints

Example 2

Input:  num = "101"
Output: true
Why:    1, 0, 1: a lone 0 is a valid number

Example 3

Input:  num = "1023"
Output: false
Why:    no cut gives three numbers that add up; "02" is not allowed

Constraints

  • 1 ≤ length of num ≤ 35
  • num holds only the digits 0 to 9
  • Pieces can be far larger than 64-bit integers

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Backtrack over every cutO(n⁵)
  2. Fix the first two, walk the restO(n³)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 35 digitsVerdict
Backtrack over every cutO(n⁵)
Passes at 35 digits; wasteful
Fix the first two, walk the restO(n³)
Best; the rest is forced

n = length of num.

Edge cases to test

  • Leading zeros. "1023" cannot use "02" as a piece, so it is false.
  • Zero as a number. "101" and "011" are true: a lone 0 is fine.
  • All zeros. "000" is 0, 0, 0 and is true.
  • Too short. "1" and "10" cannot hold three numbers, so they are false.
  • Huge numbers. A 35-digit string can hold 12-digit pieces whose sum overflows 64 bits; add them as strings.

Common mistakes

  • Parsing pieces into 64-bit integers, which overflow for long inputs.
  • Allowing pieces like "03", or banning a lone "0".
  • Returning true after only two numbers, when at least three are required.

How to talk through it

  1. 1Clarify. Are leading zeros allowed? Is a lone 0 a number? How long can the string be?
  2. 2Give the backtracking. Cut piece by piece, trying every length; say that it repeats work once the sum is known.
  3. 3Notice what is forced. The first two numbers decide everything, so loop over their lengths and only check the rest.
  4. 4Handle big numbers. Add the two numbers as strings, digit by digit, and compare with a prefix check.
  5. 5Test out loud. Run "101", "1023", "000" and a 35-digit input before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?