MediumNo. 2369

Check if There is a Valid Partition For The Array — LeetCode 2369 Python Solution

Topics
Array, Dynamic Programming
Reading time
3 min

The problem

You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.

Example

Input
nums = [4,4,4,5,6]
Output
true
Explanation
The array can be partitioned into the subarrays [4,4] and [4,5,6].

Python solution

PythonSolution
class Solution:
    def validPartition(self, nums: List[int]) -> bool:
        @cache
        def dfs(i: int) -> bool:
            if i >= n:
                return True
            a = i + 1 < n and nums[i] == nums[i + 1]
            b = i + 2 < n and nums[i] == nums[i + 1] == nums[i + 2]
            c = (
                i + 2 < n
                and nums[i + 1] - nums[i] == 1
                and nums[i + 2] - nums[i + 1] == 1
            )
            return (a and dfs(i + 2)) or ((b or c) and dfs(i + 3))

        n = len(nums)
        return dfs(0)

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2369. Check if There is a Valid Partition For The Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium
0085Maximal RectangleHard

Frequently asked questions

How hard is LeetCode 2369. Check if There is a Valid Partition For The Array?

LeetCode 2369. Check if There is a Valid Partition For The Array is rated Medium on LeetCode.

What is the time complexity of LeetCode 2369. Check if There is a Valid Partition For The Array?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 2369. Check if There is a Valid Partition For The Array?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 2369. Check if There is a Valid Partition For The Array cover?

LeetCode 2369. Check if There is a Valid Partition For The Array is tagged 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.