625. Additive Digits

Medium3.5 points estimatedStringBacktracking3 hints

A bank clerk finds a string num of digits that may be a sequence of numbers written one after another without separators. The sequence is additive if it has at least three numbers, and every number after the first two equals the sum of the two numbers just before it. A number may not start with 0 unless it is the single digit 0; all numbers are non-negative.

Return true if num can be read as an additive sequence and false otherwise. Once the first two numbers are chosen, the rest of the sequence is forced, so only the first two pieces need to be searched.

Example 1

Input:
num = "3471118"
Output:
true
Explanation:

Read as 3, 4, 7, 11, 18: each number after the first two is the sum of the previous two.

Example 2

Input:
num = "10203"
Output:
false
Explanation:

Every start fails. For example 1, 0 needs a third number 1 but the string continues with 2, and 10, 2 needs a third number 12 but only 03 is left.

Example 3

Input:
num = "2461016"
Output:
true
Explanation:

Read as 2, 4, 6, 10, 16: 2 + 4 = 6, 4 + 6 = 10, 6 + 10 = 16.

Constraints

  • 1 ≤ num.length ≤ 15
  • num consists only of digits.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n^3)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…