#3388
Count Beautiful Splits in an Array
MediumArrayDynamic ProgrammingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can use a prefix sum approach to count occurrences of each number, allowing us to efficiently check for valid splits without redundant checks.
⚙️
Algorithm
3 steps- 1Step 1: Create a count array to store occurrences of each number up to each index.
- 2Step 2: Iterate through possible split points and check prefix conditions using the count array.
- 3Step 3: Count valid splits based on the prefix conditions.
solution.py9 lines
1def count_beautiful_splits(nums):
2 count = [0] * 51
3 for num in nums:
4 count[num] += 1
5 total = 0
6 for i in range(1, len(nums) - 1):
7 if count[nums[i]] > 0:
8 total += 1
9 return totalℹ
Complexity note: The algorithm processes the array in linear time and uses a fixed-size count array for tracking occurrences.
- 1Prefix conditions are crucial for determining valid splits.
- 2Using counts can simplify checks for prefixes.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.