Ctrl K

Digits Into a Sum Chain

Medium
You are given a string digits. Cut it into pieces that form a **sum chain**: a list of non-negative integers where - there are at least three numbers; - every number from the third one on equals the sum of the two before it; - every number is at most 2³¹ − 1. A piece may not start with a zero unless the piece is exactly 0. The first two numbers determine the whole chain, so splits differ only in them. If several splits work, return the one whose first number has the fewest digits; on a tie, the one whose second number has the fewest digits. If no split works, return an empty list.
Example 1
digits="358132134" → [3, 5, 8, 13, 21, 34]

3, 5, 8, 13, 21, 34: each number is the sum of the two before it.

Example 2
digits="22325" → [2, 23, 25]

Two splits work: [2, 23, 25] and [22, 3, 25]. The first one has the shorter first number, so it is the answer.

Example 3
digits="1023" → []

After 1, 0 the next number must be 1, and after 10, 2 it must be 12; the piece 02 is not allowed because of the leading zero. No split works, so the answer is an empty list.

Constraints
  • 1 ≤ len(digits) ≤ 200
  • digits consists of digits only
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsKeypad Words MediumAll Balanced Bracket Strings MediumWord Traced on a Letter Grid MediumIP Addresses From a Digit String MediumCutting a Word Into Palindromes Medium
loading Python…
Input
digits="358132134"
Expected
[3, 5, 8, 13, 21, 34]

Run checks the first 3 tests in your browser. Submit checks all 79 tests on the server, hidden ones included.