Missing undo step on backtrack
Wrong move: Mutable state leaks between branches.
Usually fails on: Later branches inherit selections from earlier branches.
Fix: Always revert state changes immediately after recursive call.
Move from brute-force thinking to an efficient approach using backtracking strategy.
You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579].
Formally, a Fibonacci-like sequence is a list f of non-negative integers such that:
0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type),f.length >= 3, andf[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2.Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.
Return any Fibonacci-like sequence split from num, or return [] if it cannot be done.
Example 1:
Input: num = "1101111" Output: [11,0,11,11] Explanation: The output [110, 1, 111] would also be accepted.
Example 2:
Input: num = "112358130" Output: [] Explanation: The task is impossible.
Example 3:
Input: num = "0123" Output: [] Explanation: Leading zeroes are not allowed, so "01", "2", "3" is not valid.
Constraints:
1 <= num.length <= 200num contains only digits.Problem summary: You are given a string of digits num, such as "123456579". We can split it into a Fibonacci-like sequence [123, 456, 579]. Formally, a Fibonacci-like sequence is a list f of non-negative integers such that: 0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type), f.length >= 3, and f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2. Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself. Return any Fibonacci-like sequence split from num, or return [] if it cannot be done.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Backtracking
"1101111"
"112358130"
"0123"
additive-number)fibonacci-number)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #842: Split Array into Fibonacci Sequence
class Solution {
private List<Integer> ans = new ArrayList<>();
private String num;
public List<Integer> splitIntoFibonacci(String num) {
this.num = num;
dfs(0);
return ans;
}
private boolean dfs(int i) {
if (i == num.length()) {
return ans.size() >= 3;
}
long x = 0;
for (int j = i; j < num.length(); ++j) {
if (j > i && num.charAt(i) == '0') {
break;
}
x = x * 10 + num.charAt(j) - '0';
if (x > Integer.MAX_VALUE
|| (ans.size() >= 2 && x > ans.get(ans.size() - 1) + ans.get(ans.size() - 2))) {
break;
}
if (ans.size() < 2 || x == ans.get(ans.size() - 1) + ans.get(ans.size() - 2)) {
ans.add((int) x);
if (dfs(j + 1)) {
return true;
}
ans.remove(ans.size() - 1);
}
}
return false;
}
}
// Accepted solution for LeetCode #842: Split Array into Fibonacci Sequence
func splitIntoFibonacci(num string) []int {
n := len(num)
ans := []int{}
var dfs func(int) bool
dfs = func(i int) bool {
if i == n {
return len(ans) > 2
}
x := 0
for j := i; j < n; j++ {
if j > i && num[i] == '0' {
break
}
x = x*10 + int(num[j]-'0')
if x > math.MaxInt32 || (len(ans) > 1 && x > ans[len(ans)-1]+ans[len(ans)-2]) {
break
}
if len(ans) < 2 || x == ans[len(ans)-1]+ans[len(ans)-2] {
ans = append(ans, x)
if dfs(j + 1) {
return true
}
ans = ans[:len(ans)-1]
}
}
return false
}
dfs(0)
return ans
}
# Accepted solution for LeetCode #842: Split Array into Fibonacci Sequence
class Solution:
def splitIntoFibonacci(self, num: str) -> List[int]:
def dfs(i):
if i == n:
return len(ans) > 2
x = 0
for j in range(i, n):
if j > i and num[i] == '0':
break
x = x * 10 + int(num[j])
if x > 2**31 - 1 or (len(ans) > 2 and x > ans[-2] + ans[-1]):
break
if len(ans) < 2 or ans[-2] + ans[-1] == x:
ans.append(x)
if dfs(j + 1):
return True
ans.pop()
return False
n = len(num)
ans = []
dfs(0)
return ans
// Accepted solution for LeetCode #842: Split Array into Fibonacci Sequence
struct Solution;
impl Solution {
fn split_into_fibonacci(s: String) -> Vec<i32> {
let mut cur = vec![];
let mut res = vec![];
Self::dfs(0, &mut cur, &mut res, &s, s.len());
res
}
fn dfs(start: usize, cur: &mut Vec<i32>, res: &mut Vec<i32>, s: &str, end: usize) {
if start == end && cur.len() > 2 {
*res = cur.to_vec();
} else {
for i in 1..=(end - start) {
let t = &s[start..start + i];
if &s[start..start + 1] == "0" && i > 1 {
break;
}
if let Ok(x) = t.parse::<i32>() {
let n = cur.len();
if n < 2 {
cur.push(x);
Self::dfs(start + i, cur, res, s, end);
cur.pop();
} else {
if x > cur[n - 1] + cur[n - 2] {
break;
}
if x == cur[n - 1] + cur[n - 2] {
cur.push(x);
Self::dfs(start + i, cur, res, s, end);
cur.pop();
}
}
} else {
break;
}
}
}
}
}
#[test]
fn test() {
let s = "123456579".to_string();
let res = vec![123, 456, 579];
assert_eq!(Solution::split_into_fibonacci(s), res);
let s = "11235813".to_string();
let res = vec![1, 1, 2, 3, 5, 8, 13];
assert_eq!(Solution::split_into_fibonacci(s), res);
let s = "112358130".to_string();
let res: Vec<i32> = vec![];
assert_eq!(Solution::split_into_fibonacci(s), res);
let s = "0123".to_string();
let res: Vec<i32> = vec![];
assert_eq!(Solution::split_into_fibonacci(s), res);
let s = "1101111".to_string();
let res = vec![110, 1, 111];
assert_eq!(Solution::split_into_fibonacci(s), res);
}
// Accepted solution for LeetCode #842: Split Array into Fibonacci Sequence
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #842: Split Array into Fibonacci Sequence
// class Solution {
// private List<Integer> ans = new ArrayList<>();
// private String num;
//
// public List<Integer> splitIntoFibonacci(String num) {
// this.num = num;
// dfs(0);
// return ans;
// }
//
// private boolean dfs(int i) {
// if (i == num.length()) {
// return ans.size() >= 3;
// }
// long x = 0;
// for (int j = i; j < num.length(); ++j) {
// if (j > i && num.charAt(i) == '0') {
// break;
// }
// x = x * 10 + num.charAt(j) - '0';
// if (x > Integer.MAX_VALUE
// || (ans.size() >= 2 && x > ans.get(ans.size() - 1) + ans.get(ans.size() - 2))) {
// break;
// }
// if (ans.size() < 2 || x == ans.get(ans.size() - 1) + ans.get(ans.size() - 2)) {
// ans.add((int) x);
// if (dfs(j + 1)) {
// return true;
// }
// ans.remove(ans.size() - 1);
// }
// }
// return false;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Generate every possible combination without any filtering. At each of n positions we choose from up to n options, giving nⁿ total candidates. Each candidate takes O(n) to validate. No pruning means we waste time on clearly invalid partial solutions.
Backtracking explores a decision tree, but prunes branches that violate constraints early. Worst case is still factorial or exponential, but pruning dramatically reduces the constant factor in practice. Space is the recursion depth (usually O(n) for n-level decisions).
Review these before coding to avoid predictable interview regressions.
Wrong move: Mutable state leaks between branches.
Usually fails on: Later branches inherit selections from earlier branches.
Fix: Always revert state changes immediately after recursive call.