Count Beautiful Splits in an Array Problem
#3388
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3388.
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:
1. A split with nums1 = [1], nums2 = [1,2], nums3 = [1].
2. 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
Solution
Approach: Longest common prefix table + enumeration
Precompute lcp[i][j], the length of the longest common prefix of nums[i:] and nums[j:], from the back: if nums[i] == nums[j] then lcp[i][j] = lcp[i + 1][j + 1] + 1, otherwise 0.
Then enumerate the two cut positions i < j, giving parts of length i, j - i and n - j. The first part is a prefix of the second when i <= j - i and lcp[0][i] >= i. The second is a prefix of the third when j - i <= n - j and lcp[i][j] >= j - i. If either holds, the split is beautiful. Count them.
Complexity: Time O(n^2), space O(n^2).
class Solution:
def beautifulSplits(self, nums: List[int]) -> int:
n = len(nums)
lcp = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for j in range(n - 1, i - 1, -1):
if nums[i] == nums[j]:
lcp[i][j] = lcp[i + 1][j + 1] + 1
ans = 0
for i in range(1, n - 1):
for j in range(i + 1, n):
a = i <= j - i and lcp[0][i] >= i
b = j - i <= n - j and lcp[i][j] >= j - i
ans += int(a or b)
return ans