Check if There is a Valid Partition For The Array Problem
#2369
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2369.
You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.
We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:
- The subarray consists of exactly
2,equal elements. For example, the subarray[2,2]is good. - The subarray consists of exactly
3,equal elements. For example, the subarray[4,4,4]is good. - The subarray consists of exactly
3consecutive increasing elements, that is, the difference between adjacent elements is1. For example, the subarray[3,4,5]is good, but the subarray[1,3,5]is not.
Return true if the array has at least one valid partition. Otherwise, return false.
Example 1:
Input: nums = [4,4,4,5,6]
Output: true
Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6].
This partition is valid, so we return true.
Example 2:
Input: nums = [1,1,1,2]
Output: false
Explanation: There is no valid partition for this array.
Constraints:
2 <= nums.length <= 10^51 <= nums[i] <= 10^6
Solution
Approach: Memoized Recursion
Let dfs(i) tell whether the suffix starting at i can be split validly. An empty suffix (i >= n) is valid. Otherwise the first piece is one of:
- two equal elements, then continue at
i + 2; - three equal elements, then continue at
i + 3; - three consecutive increasing elements (each one more than the previous), then continue at
i + 3.
dfs(i) is true if any of these pieces fits and the rest is valid. Each index is computed once and cached.
Complexity: O(n) time and O(n) space.
from functools import lru_cache
class Solution:
def validPartition(self, nums: List[int]) -> bool:
@lru_cache(None)
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)