algoadvance

Leetcode 306. Additive Number

Problem Statement

An additive number is a string whose digits can form an additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

Given a string containing only digits, return true if it is an additive number or false otherwise.

Example 1:

Input: "112358"
Output: true
Explanation: The digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
             1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8

Example 2:

Input: "199100199"
Output: true
Explanation: The additive sequence is: 1, 99, 100, 199.
             1 + 99 = 100, 99 + 100 = 199

Constraints:

Clarifying Questions

  1. Can the sequence start with 0?
    • Yes, but if a number starts with 0, it should be exactly 0 because we don’t want leading zeroes in any part of the sequence.
  2. Can the input be empty?
    • No, per constraints, the length is between 1 and 35.

Strategy

  1. Iterate through possible first and second numbers:
    • Use two nested loops to determine the first and second numbers in the sequence.
    • Ensure numbers don’t have leading zeros unless they are exactly 0.
  2. Formulate the additive sequence:
    • Once you identify the first and second numbers, use a loop to generate subsequent numbers.
    • Check if the substring of the sum matches the actual numbers in the original string.
  3. Early termination:
    • If a sequence fails to match at any point, terminate early.

Code

Here’s the implementation of the described strategy:

public class Solution {
    public boolean isAdditiveNumber(String num) {
        int n = num.length();
        
        for (int i = 1; i <= n / 2; i++) {
            if (num.charAt(0) == '0' && i > 1) return false; // Leading zero case
            Long num1 = Long.parseLong(num.substring(0, i));
            
            for (int j = i + 1; n - j >= j - i && n - j >= i; j++) {
                if (num.charAt(i) == '0' && j - i > 1) break; // Leading zero case
                Long num2 = Long.parseLong(num.substring(i, j));
                if (isValid(num, num1, num2, j)) return true;
            }
        }
        return false;
    }
    
    private boolean isValid(String num, Long num1, Long num2, int start) {
        int n = num.length();
        while (start < n) {
            num2 = num2 + num1;
            num1 = num2 - num1;
            String sumStr = num2.toString();
            if (!num.startsWith(sumStr, start)) return false;
            start += sumStr.length();
        }
        return true;
    }
    
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.isAdditiveNumber("112358")); // true
        System.out.println(solution.isAdditiveNumber("199100199")); // true
        System.out.println(solution.isAdditiveNumber("123")); // true
        System.out.println(solution.isAdditiveNumber("1023")); // false
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI