#2369
Check if There is a Valid Partition For The Array
MediumArrayDynamic ProgrammingDynamic ProgrammingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses dynamic programming to build a solution incrementally. We maintain a DP array where each entry indicates if the subarray up to that index can be partitioned validly.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a DP array of size n+1 with false values, set DP[0] to true.
- 2Step 2: Iterate through the nums array, checking for valid partitions of size 2 and 3.
- 3Step 3: Update the DP array based on the conditions for valid partitions.
- 4Step 4: Return the value of DP[n] to determine if the entire array can be partitioned.
solution.py10 lines
1def hasValidPartition(nums):
2 n = len(nums)
3 dp = [False] * (n + 1)
4 dp[0] = True
5 for i in range(2, n + 1):
6 if nums[i - 1] == nums[i - 2]:
7 dp[i] = dp[i] or dp[i - 2]
8 if i > 2 and (nums[i - 1] == nums[i - 2] == nums[i - 3] or (nums[i - 1] == nums[i - 2] + 1 and nums[i - 2] == nums[i - 3] + 1)):
9 dp[i] = dp[i] or dp[i - 3]
10 return dp[n]ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the array, and the space complexity is O(n) due to the DP array we maintain.
- 1Dynamic programming is a powerful technique for problems involving partitions or subsequences.
- 2Recognizing valid patterns in subarrays can significantly reduce the complexity of the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.