#306
Additive Number
MediumStringBacktrackingBacktrackingString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
We can optimize the brute force approach by using backtracking to validate the sequence more efficiently. Instead of checking all combinations, we will directly build the sequence and validate it as we go.
⚙️
Algorithm
3 steps- 1Step 1: Define a recursive function that takes the current index, the first two numbers, and the string.
- 2Step 2: Check if the current index has reached the end of the string and if we have at least three numbers in the sequence.
- 3Step 3: Generate the next number by adding the first two numbers and check if it matches the substring starting from the current index.
solution.py24 lines
1# Full working Python code
2
3def isAdditiveNumber(num):
4 def backtrack(index, first, second):
5 if index == len(num):
6 return True
7 next_num = str(int(first) + int(second))
8 if not num.startswith(next_num, index):
9 return False
10 return backtrack(index + len(next_num), second, next_num)
11
12 n = len(num)
13 for i in range(1, n):
14 for j in range(i + 1, n):
15 first = num[:i]
16 second = num[i:j]
17 if (len(first) > 1 and first[0] == '0') or (len(second) > 1 and second[0] == '0'):
18 continue
19 if backtrack(j, first, second):
20 return True
21 return False
22
23# Example usage
24print(isAdditiveNumber('112358')) # Output: Trueℹ
Complexity note: The time complexity remains O(n²) due to the nested loops for selecting the first two numbers, but the recursive backtracking reduces unnecessary checks. The space complexity is O(n) because of the recursive call stack.
- 1The sequence must have at least three numbers.
- 2Leading zeros are not allowed unless the number is '0'.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.