Problem solution · C++

Count Beautiful Splits in an Array

Count Beautiful Splits in an Array: a C++ solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sliding window or two pointers
Source
walkccc LeetCode Solutions
Length
44 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Count Beautiful Splits in an Array, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 44 lines of C++ from the credited upstream file 3388.cpp.
  • The implementation visibly relies on sequence storage.
  • 5 loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeCount Beautiful Splits in an Array · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  int beautifulSplits(vector<int>& nums) {    const int n = nums.size();    int ans = 0;    // z[start][i] := the z array of nums[i..n) with respect to nums[start..n)    vector<vector<int>> z;     for (int start = 0; start < n; ++start)      z.push_back(zFunction(nums, start));     // nums1 | nums2 | nums3 = nums[0..i] | nums[i + 1..j] | nums[j + 1..n - 1]    for (int i = 0; i < n - 2; ++i)      for (int j = i + 1; j < n - 1; ++j)        if ((j - i >= i + 1 &&             z[0][i + 1] >= i + 1) ||  // nums1 is a prefix of nums2.            z[i + 1][j + 1] >= j - i)  // nums2 is a suffix of nums3.          ++ans;     return ans;  }  private:  // Returns the z array, where z[i] is the length of the longest prefix of  // nums[i..n) which is also a prefix of nums[start..n).  vector<int> zFunction(const vector<int>& nums, int start) {    const int n = nums.size();    vector<int> z(n);    int l = 0;    int r = 0;    for (int i = 1 + start; i < n; ++i) {      if (i < r)        z[i] = min(r - i, z[i - l + start]);      while (i + z[i] < n && nums[z[i] + start] == nums[i + z[i]])        ++z[i];      if (i + z[i] > r) {        l = i;        r = i + z[i];      }    }    return z;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗