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

MediumArrayDynamic Programming
Problem
#2369
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

Python
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

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

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

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.

Get Stealth Interview