MediumNo. 2811

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

Pattern
Greedy
Topics
Greedy, Array, Dynamic Programming
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

PythonSolution
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

Time
O(n3)
Space · auxiliary
O(n2)where n is the length of the array nums

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

Related problems
No.ProblemDifficulty
0045Jump Game IIMedium
0055Jump GameMedium
0122Best Time to Buy and Sell Stock IIMedium
0376Wiggle SubsequenceMedium
0435Non-overlapping IntervalsMedium
0646Maximum Length of Pair ChainMedium

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(n3).

What is the space complexity of LeetCode 2811. Check if it is Possible to Split Array?

The Python solution on this page uses O(n2), 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.

Free to download. Check it runs on your machine, then pick a plan.