Check if There is a Valid Partition For The Array - Problem

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 3 consecutive increasing elements, that is, the difference between adjacent elements is 1. 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.

Input & Output

Example 1 — Valid Partition Exists
$ Input: nums = [4,4,4,5,6]
Output: false
💡 Note: We can form [4,4,4] (three equal elements) but [5,6] is invalid since 5≠6 (not equal elements). Therefore, no valid partition exists.
Example 2 — Three Equal Elements
$ Input: nums = [4,4,4]
Output: true
💡 Note: The entire array [4,4,4] consists of exactly 3 equal elements, which is a valid subarray.
Example 3 — Consecutive Sequence
$ Input: nums = [1,2,3]
Output: true
💡 Note: The entire array [1,2,3] consists of exactly 3 consecutive increasing elements (difference of 1 between adjacent elements).

Constraints

  • 2 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Valid Partition Problem - DP Approach INPUT nums array: 4 [0] 4 [1] 4 [2] 5 [3] 6 [4] Valid Subarray Rules: 1. Two equal: [2,2] 2. Three equal: [4,4,4] 3. Three consecutive: [3,4,5] Goal: Partition entire array using valid subarrays only ALGORITHM STEPS 1 Define DP Array dp[i] = can partition nums[0..i-1] 2 Base Case dp[0] = true (empty valid) 3 Transitions Check 2-elem and 3-elem rules 4 Return Answer dp[n] is the result DP Table Computation: i: 0 1 2 3 4 5 dp: T F T T F T dp[3]=T: [4,4,4] three equal dp[5]=T: [4,5,6] consecutive FINAL RESULT Valid Partition Found: [4,4,4] 3 equal + [4,5,6] consecutive Output: true OK - Valid Partition Both subarrays satisfy the given rules Time: O(n) | Space: O(n) Key Insight: DP allows us to build valid partitions incrementally. At each position i, we check if we can extend a valid partition by adding a 2-element or 3-element valid subarray ending at position i. dp[i] = dp[i-2] AND (2-equal) OR dp[i-3] AND (3-equal OR 3-consecutive) TutorialsPoint - Check if There is a Valid Partition For The Array | DP Approach
Asked in
Google 15 Amazon 12 Meta 8
18.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen