Count Beautiful Splits in an Array - Problem

You are given an array nums. A split of an array nums is beautiful if:

  • The array nums is split into three subarrays: nums1, nums2, and nums3, such that nums can be formed by concatenating nums1, nums2, and nums3 in that order.
  • The subarray nums1 is a prefix of nums2 OR nums2 is a prefix of nums3.

Return the number of ways you can make this split.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,1,2,1]
Output: 2
💡 Note: Split 1: nums1=[1], nums2=[1], nums3=[2,1] - nums1 is prefix of nums2. Split 2: nums1=[1], nums2=[1,2], nums3=[1] - nums1 is prefix of nums2.
Example 2 — Single Valid Split
$ Input: nums = [1,2,1,2,1]
Output: 2
💡 Note: Split 1: nums1=[1], nums2=[2,1,2], nums3=[1] - nums2 is prefix of nums3. Split 2: nums1=[1,2,1], nums2=[2], nums3=[1] - nums2 is prefix of nums3.
Example 3 — No Valid Splits
$ Input: nums = [1,2,3]
Output: 0
💡 Note: Only possible split: nums1=[1], nums2=[2], nums3=[3] - neither nums1 is prefix of nums2 nor nums2 is prefix of nums3.

Constraints

  • 3 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 40

Visualization

Tap to expand
Count Beautiful Splits in an Array INPUT Array: nums 1 i=0 1 i=1 2 i=2 1 i=3 Split into 3 subarrays: nums1 | nums2 | nums3 Beautiful Split Condition: nums1 is prefix of nums2 OR nums2 is prefix of nums3 Input Values: nums = [1, 1, 2, 1] ALGORITHM STEPS 1 Preprocess LCP Build Longest Common Prefix array for pairs 2 Iterate Split Points Try all i (end of nums1) Try all j (end of nums2) 3 Check Prefix Condition Use LCP to check if len1 <= LCP(0,i) or len2 <= LCP(i,j) 4 Count Valid Splits Increment counter for each beautiful split LCP enables O(1) prefix check Time: O(n^2), Space: O(n^2) FINAL RESULT Valid Beautiful Splits: Split 1: 1 1 2,1 [1] prefix of [1] - OK Split 2: 1 1,2 1 [1] prefix of [1,2] - OK Output: 2 Beautiful Splits Result Verified! 2 ways to split array Key Insight: The LCP (Longest Common Prefix) array enables O(1) prefix checks. LCP[i][j] stores the length of the longest common prefix between subarrays starting at i and j. A subarray A is a prefix of B if len(A) <= LCP[start_A][start_B]. This avoids O(n) comparisons for each split check. TutorialsPoint - Count Beautiful Splits in an Array | Optimized with Preprocessing
Asked in
Google 15 Amazon 12
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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