The Count Beautiful Splits in an Array coding problem asks you to find the number of ways to split an array into three non-empty contiguous parts: nums1, nums2, nums3. A split is "beautiful" if at least one of these conditions is met:
nums1 is a prefix of nums2.nums2 is a prefix of nums3.Amazon and Bloomberg use this Array interview pattern to test your efficiency with prefix and string matching logic. It’s a "Medium" problem because an O(N^3) solution (trying all splits and checking prefixes) is too slow. It evaluates if you can optimize the prefix check to O(1) or O(log N) using a Longest Common Prefix (LCP) array or Z-algorithm.
The problem is best solved using Precomputation (Z-algorithm or LCP).
i and j (where nums1 = [0..i-1], nums2 = [i..j-1], nums3 = [j..n-1]).LCP(0, i) >= i (meaning nums1 is a prefix of nums2) or if LCP(i, j) >= j - i (meaning nums2 is a prefix of nums3).nums = [1, 2, 1, 2, 1, 2, 1]
[1, 2], [1, 2, 1, 2], [1].nums1 is [1, 2]. nums2 starts with [1, 2, ...].nums1 is a prefix of nums2). This is a beautiful split.array.slice().equals() in every loop, which turns an O(N^2) search into O(N^3).nums1, nums2, and nums3.Master the Z-algorithm. It allows you to find all occurrences of a pattern (or in this case, a prefix) in linear time, which is a common requirement for "Medium" and "Hard" array/string problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Minimum Array Sum | Medium | Solve | |
| Paint House IV | Medium | Solve | |
| Last Stone Weight II | Medium | Solve | |
| Maximum Alternating Subarray Sum | Medium | Solve | |
| Filling Bookcase Shelves | Medium | Solve |