LeetCode 3388: Count Beautiful Splits in an Array Solution

Master LeetCode problem 3388 (Count Beautiful Splits in an Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3388. Count Beautiful Splits in an Array

Problem Explanation

Explanation:

To solve this problem, we can iterate through all possible splits of the array and check if the conditions for a beautiful split are satisfied. We can keep track of the frequency of each element in the array to optimize the checking process. The conditions for a beautiful split are:

  1. The array can be split into three subarrays.
  2. The first subarray is a prefix of the second subarray.
  3. The second subarray is a prefix of the third subarray.

We can iterate through the array and calculate the prefix sum of element frequencies to check if the split conditions are met. The total number of beautiful splits can be calculated based on these conditions.

:

Solution Code

class Solution {
    public int countBeautifulSplits(int[] nums) {
        int n = nums.length;
        int[] prefixFreq = new int[51];
        int result = 0;
        int count1 = 0, count2 = 0;
        
        for (int i = 0; i < n - 1; i++) {
            prefixFreq[nums[i]]++;
            count1++;
            for (int j = n - 1; j > i; j--) {
                if (prefixFreq[nums[j]] == 0) {
                    count2++;
                } else {
                    prefixFreq[nums[j]]--;
                    if (--count1 == count2) {
                        result++;
                    }
                }
            }
            count1 = 0;
            count2 = 0;
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3388 (Count Beautiful Splits in an Array)?

This page provides optimized solutions for LeetCode problem 3388 (Count Beautiful Splits in an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3388 (Count Beautiful Splits in an Array)?

The time complexity for LeetCode 3388 (Count Beautiful Splits in an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3388 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3388 in Java, C++, or Python.

Back to LeetCode Solutions