Split the Array - Problem

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.

Input & Output

Example 1 — Basic Valid Split
$ Input: nums = [1,1,2,2]
Output: true
💡 Note: We can split into [1,2] and [1,2]. Both groups have distinct elements.
Example 2 — Impossible Split
$ Input: nums = [1,1,1,1]
Output: false
💡 Note: Element 1 appears 4 times. Cannot split into two distinct groups of size 2.
Example 3 — Mixed Frequencies
$ Input: nums = [1,1,2,3]
Output: true
💡 Note: Can split into [1,2] and [1,3]. Each group has distinct elements.

Constraints

  • 2 ≤ nums.length ≤ 100
  • nums.length is even
  • -100 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Split the Array - Hash Approach INPUT nums = [1, 1, 2, 2] 1 idx 0 1 idx 1 2 idx 2 2 idx 3 Properties: • Array length: 4 (even) • Half size: 2 Constraint: Each element can appear at most twice ALGORITHM STEPS 1 Count Frequencies Use HashMap to count 1 --> 2 2 --> 2 (key: count) 2 Check Max Count Max count must be <= 2 3 Validate Split If count > 2: impossible 4 Return Result All counts <= 2: true Why count <= 2? Each element goes to nums1 or nums2 (both need distinct) So max 2 copies allowed FINAL RESULT Valid Split Found: nums1 (distinct) 1 2 nums2 (distinct) 1 2 Output: true Both halves have distinct elements: OK Length = 2 each: OK Key Insight: The split is possible if and only if no element appears more than twice in the original array. With max 2 occurrences, one copy goes to nums1 and one to nums2, keeping both distinct. Time: O(n) for counting | Space: O(n) for HashMap TutorialsPoint - Split the Array | Hash Approach
Asked in
Amazon 15 Microsoft 12
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen