3046. Split the Array LeetCode Solution

In this guide, you will get 3046. Split the Array LeetCode Solution with the best time and space complexity. The solution to Split the Array problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Split the Array solution in C++
  4. Split the Array solution in Java
  5. Split the Array solution in Python
  6. Additional Resources
3046. Split the Array LeetCode Solution image

Problem Statement of Split the Array

You are given an integer array nums of even length. You have to split the array into two parts nums1 and nums2 such that:

nums1.length == nums2.length == nums.length / 2.
nums1 should contain distinct elements.
nums2 should also contain distinct elements.

Return true if it is possible to split the array, and false otherwise.

Example 1:

Input: nums = [1,1,2,2,3,4]
Output: true
Explanation: One of the possible ways to split nums is nums1 = [1,2,3] and nums2 = [1,2,4].

Example 2:

Input: nums = [1,1,1,1]
Output: false
Explanation: The only possible way to split nums is nums1 = [1,1] and nums2 = [1,1]. Both nums1 and nums2 do not contain distinct elements. Therefore, we return false.

Constraints:

1 <= nums.length <= 100
nums.length % 2 == 0
1 <= nums[i] <= 100

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(100) = O(1)

3046. Split the Array LeetCode Solution in C++

class Solution {
 public:
  bool isPossibleToSplit(vector<int>& nums) {
    constexpr int kMax = 100;
    vector<int> count(kMax + 1);

    for (const int num : nums)
      ++count[num];

    return ranges::all_of(count, [](int freq) { return freq <= 2; });
  }
};
/* code provided by PROGIEZ */

3046. Split the Array LeetCode Solution in Java

class Solution {
  public boolean isPossibleToSplit(int[] nums) {
    final int kMax = 100;
    int[] count = new int[kMax + 1];

    for (final int num : nums)
      ++count[num];

    return Arrays.stream(count).allMatch(freq -> freq <= 2);
  }
}
// code provided by PROGIEZ

3046. Split the Array LeetCode Solution in Python

class Solution:
  def isPossibleToSplit(self, nums: list[int]) -> bool:
    return all(freq <= 2 for freq in collections.Counter(nums).values())
# code by PROGIEZ

Additional Resources

See also  1531. String Compression II LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.