3388. Count Beautiful Splits in an Array
Description
You are given an array nums.
A split of an array nums is beautiful if:
- The array
numsis split into three subarrays:nums1,nums2, andnums3, such thatnumscan be formed by concatenatingnums1,nums2, andnums3in that order. - The subarray
nums1is a prefix ofnums2ORnums2is a prefix ofnums3.
Return the number of ways you can make this split.
Example 1:
Input: nums = [1,1,2,1]
Output: 2
Explanation:
The beautiful splits are:
- A split with
nums1 = [1],nums2 = [1,2],nums3 = [1]. - A split with
nums1 = [1],nums2 = [1],nums3 = [2,1].
Example 2:
Input: nums = [1,2,3,4]
Output: 0
Explanation:
There are 0 beautiful splits.
Constraints:
1 <= nums.length <= 50000 <= nums[i] <= 50
Solutions
Solution 1: LCP + Enumeration
Thinking
We split into three parts so that the first is a prefix of the second, or the second is a prefix of the third. With \(n \le 5000\) two cut points are \(O(n^2)\), but a naive prefix compare would add another linear factor.
\(\textit{lcp}[i][j]\) is the LCP of the two suffixes, built backward from \(\textit{lcp}[i+1][j+1]\), after which a compare is \(O(1)\).
Cuts \((i,j)\) are beautiful when \(\textit{lcp}[0][i] \ge i\) or \(\textit{lcp}[i][j] \ge j-i\), with the obvious length constraints.
We can preprocess \(\text{LCP}[i][j]\) to represent the length of the longest common prefix of \(\textit{nums}[i:]\) and \(\textit{nums}[j:]\). Initially, \(\text{LCP}[i][j] = 0\).
Next, we enumerate \(i\) and \(j\) in reverse order. For each pair of \(i\) and \(j\), if \(\textit{nums}[i] = \textit{nums}[j]\), then we can get \(\text{LCP}[i][j] = \text{LCP}[i + 1][j + 1] + 1\).
Finally, we enumerate the ending position \(i\) of the first subarray (excluding position \(i\)) and the ending position \(j\) of the second subarray (excluding position \(j\)). The length of the first subarray is \(i\), the length of the second subarray is \(j - i\), and the length of the third subarray is \(n - j\). If \(i \leq j - i\) and \(\text{LCP}[0][i] \geq i\), or \(j - i \leq n - j\) and \(\text{LCP}[i][j] \geq j - i\), then this split is beautiful, and we increment the answer by one.
After enumerating, the answer is the number of beautiful splits.
The time complexity is \(O(n^2)\), and the space complexity is \(O(n^2)\). Here, \(n\) is the length of the array \(\textit{nums}\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |