Count Beautiful Splits in an Array - Problem
You are given an integer array nums. Your task is to find all possible ways to split this array into three non-empty subarrays such that the split is considered "beautiful".
A split is beautiful if:
- The array
numsis divided into exactly three consecutive subarrays:nums1,nums2, andnums3 - At least one of the following conditions is met:
nums1is a prefix ofnums2, ORnums2is a prefix ofnums3
Note: Array A is a prefix of array B if A can be obtained by taking the first few elements of B. For example, [1, 2] is a prefix of [1, 2, 3, 4].
Goal: Return the total number of beautiful splits possible.
Input & Output
example_1.py โ Basic Case
$
Input:
[1,1,2,1]
โบ
Output:
2
๐ก Note:
Two beautiful splits exist: (1) Split at positions 1,2 giving [1], [1], [2,1] where nums1 is prefix of nums2. (2) Split at positions 1,3 giving [1], [1,2], [1] where nums1 is prefix of nums2.
example_2.py โ No Beautiful Splits
$
Input:
[1,2,3,4]
โบ
Output:
0
๐ก Note:
No matter how we split this array into three parts, neither prefix condition can be satisfied since all elements are distinct and increasing.
example_3.py โ Multiple Patterns
$
Input:
[1,2,1,2,1,2]
โบ
Output:
8
๐ก Note:
Multiple beautiful splits are possible due to the repeating pattern [1,2]. Many combinations satisfy either nums1 being a prefix of nums2 or nums2 being a prefix of nums3.
Constraints
- 3 โค nums.length โค 5000
- 1 โค nums[i] โค 109
- Each split must create exactly three non-empty subarrays
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Problem
We need to split array into 3 parts where either first is prefix of second OR second is prefix of third
2
Apply Z-Algorithm
Precompute all prefix relationships to avoid redundant comparisons
3
Check All Splits
For each valid split point combination, use precomputed values to check conditions
4
Count Valid Splits
Sum all combinations that satisfy at least one prefix condition
Key Takeaway
๐ฏ Key Insight: By preprocessing with Z-Algorithm, we transform expensive O(n) prefix checks into O(1) lookups, making the overall solution efficient enough for the given constraints.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code