Array of Doubled Pairs - Problem

Given an integer array arr of even length, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise.

In other words, we need to check if we can pair up all elements such that each pair contains a number and its double.

Input & Output

Example 1 — Basic Valid Case
$ Input: arr = [1,2,4,16,8,4]
Output: true
💡 Note: We can reorder as [1,2,4,8,4,16] where arr[1]=2×arr[0], arr[3]=2×arr[2], arr[5]=2×arr[4]
Example 2 — Impossible Case
$ Input: arr = [2,1,2,6]
Output: false
💡 Note: We have two 2s but only one 1 and one 6. We can pair (1,2) but the remaining 2 cannot pair with 6 since 6≠2×2
Example 3 — Zeros
$ Input: arr = [4,-2,2,-4]
Output: true
💡 Note: We can pair (-2,-4) since -4 = 2×(-2) and (2,4) since 4 = 2×2

Constraints

  • 1 ≤ arr.length ≤ 1000
  • arr.length is even
  • -1000 ≤ arr[i] ≤ 1000

Visualization

Tap to expand
Array of Doubled Pairs INPUT arr = [1,2,4,16,8,4] 1 2 4 16 8 4 0 1 2 3 4 5 Goal: Pair each number with its double Count Map: 1 --> 1 2 --> 1 4 --> 2 8 --> 1 16 --> 1 Length: 6 (even) ALGORITHM STEPS 1 Count Frequencies Build hashmap of counts 2 Sort by Abs Value [1, 2, 4, 4, 8, 16] 3 Greedy Pairing For each x, find 2*x 4 Validate Pairs All paired = true Pairing Process: 1 --> 2 OK 2 --> 4 OK 4 --> 8 OK 8 --> 16 FINAL RESULT true All elements can be paired! Valid Pairs Found: (1, 2) (2, 4) (4, 8) (8, 16) Total: 3 pairs from 6 elements Each x has matching 2*x Reordering is POSSIBLE Key Insight: Sort by absolute value and greedily match smallest numbers first. This ensures we don't "use up" a larger number that might be needed as someone else's double. TutorialsPoint - Array of Doubled Pairs | Optimal Solution O(n log n)
Asked in
Google 42 Facebook 28 Amazon 35
32.0K Views
Medium Frequency
~25 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