Checking if an Array Can Be Split into Two Distinct Halves

Given an integer array nums of even length, you need to split it into two arrays, nums1 and nums2, such that:

  • nums1.length == nums2.length == nums.length / 2.
  • nums1 contains distinct elements.
  • nums2 also contains distinct elements.

If such a split is posssible, return true; otherwise, return false.

Examples

Example 1:

Input: nums = [1,1,2,2,3,4]
Output: true
Explanation: One valid split is nums1 = [1,2,3] and nums2 = [1,2,4].

Example 2:

Input: nums = [1,1,1,1]
Output: false
Explanation: The only possible split is nums1 = [1,1] and nums2 = [1,1], but both contain duplicate elements.

Constraints

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

Approach

The problem requires splitting the oriignal array into two arrrays of equal length, each containing only distinct numbers. This implies that any number in the original array must appear at most twice; otherwise, it would be impossible to assign duplicates to two different halves while keeping both halves free of duplicates. Therefore, we can simply count the occurrences of each element in nums. If any element appears more than twice, the answer is false. Otherwise, it is always possible to form the two halves (for instance, by greedily distributing duplicates into different halves).

Code

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var canSplitIntoTwoDistinctHalves = function(nums) {
    const frequency = {};
    
    for (const value of nums) {
        frequency[value] = (frequency[value] || 0) + 1;
        if (frequency[value] > 2) {
            return false;
        }
    }
    
    return true;
};

Tags: algorithm array Hash Table javascript LeetCode

Posted on Fri, 02 Oct 2026 16:39:13 +0000 by rfighter