Split the Array Problem
#3046
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3046.
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.nums1should contain distinct elements.nums2should 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 <= 100nums.length % 2 == 01 <= nums[i] <= 100
Solution
Approach: Counting
Each half must contain distinct values, so a value can appear at most twice overall: once in each half. Conversely, if no value appears three or more times, put one copy of every value that appears twice into each half; the values that appear once fill the halves evenly, since the total length is even. So count the occurrences and return false as soon as some value reaches 3.
Complexity: time O(n), space O(n) (or O(1) with a fixed-size count array, as values are at most 100).
class Solution:
def isPossibleToSplit(self, nums: List[int]) -> bool:
return max(Counter(nums).values()) < 3