LeetCode 2578: Split With Minimum Sum Solution

Master LeetCode problem 2578 (Split With Minimum Sum), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2578. Split With Minimum Sum

Problem Explanation

Explanation

To solve this problem, we can follow these steps:

  1. Iterate through the digits of the given number from left to right.
  2. For each digit, assign it to one of the two numbers such that the sum of each digit's occurrence in the two numbers equals the total occurrence in the given number.
  3. Keep track of the minimum sum obtained by comparing the current sum after each assignment.

The time complexity of this approach is O(N), where N is the number of digits in the given number. The space complexity is O(1) as we are using a constant amount of extra space.

Solution Code

class Solution {
    public int minSumOfLengths(int[] arr, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        int sum = 0, minLen = Integer.MAX_VALUE, result = Integer.MAX_VALUE;
        
        Map<Integer, Integer> dp = new HashMap<>();
        
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
            map.put(sum, i);
        }
        
        sum = 0;
        
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
            if (map.containsKey(sum - target)) {
                int len1 = i - map.get(sum - target);
                int len2 = dp.getOrDefault(map.get(sum - target), Integer.MAX_VALUE);
                if (len2 != Integer.MAX_VALUE) {
                    result = Math.min(result, len1 + len2);
                }
                minLen = Math.min(minLen, len1);
                dp.put(i, minLen);
            }
        }
        
        return result == Integer.MAX_VALUE ? -1 : result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2578 (Split With Minimum Sum)?

This page provides optimized solutions for LeetCode problem 2578 (Split With Minimum Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2578 (Split With Minimum Sum)?

The time complexity for LeetCode 2578 (Split With Minimum Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2578 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2578 in Java, C++, or Python.

Back to LeetCode Solutions