Check if it is Possible to Split Array — LeetCode 2811 Python Solution

MediumGreedyArrayDynamic Programming
Problem
#2811
Pattern
Greedy
Reading time
3 min

The problem

You are given an array nums of length n and an integer m. You need to determine if it is possible to split the array into n arrays of size 1 by performing a series of steps.

Python solution

Python
class Solution:
    def canSplitArray(self, nums: List[int], m: int) -> bool:
        @cache
        def dfs(i: int, j: int) -> bool:
            if i == j:
                return True
            for k in range(i, j):
                a = k == i or s[k + 1] - s[i] >= m
                b = k == j - 1 or s[j + 1] - s[k + 1] >= m
                if a and b and dfs(i, k) and dfs(k + 1, j):
                    return True
            return False

        s = list(accumulate(nums, initial=0))
        return dfs(0, len(nums) - 1)

Complexity

MeasureComplexity
TimeO(n^3)
SpaceO(n^2), where n is the length of the array nums auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2811. Check if it is Possible to Split Array is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2811. Check if it is Possible to Split Array?
LeetCode 2811. Check if it is Possible to Split Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 2811. Check if it is Possible to Split Array?
The Python solution on this page runs in O(n^3).
What is the space complexity of LeetCode 2811. Check if it is Possible to Split Array?
The Python solution on this page uses O(n^2), where n is the length of the array nums auxiliary space.
What topics does LeetCode 2811. Check if it is Possible to Split Array cover?
LeetCode 2811. Check if it is Possible to Split Array is tagged Greedy, Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview