Array of Doubled Pairs - Problem
Array of Doubled Pairs asks you to determine if an array can be rearranged into a specific pattern where every pair consists of a number and its double.

Given an integer array arr of even length, return true if it's possible to reorder the array such that for every valid index i: arr[2*i + 1] = 2 * arr[2*i].

In other words, can you arrange the array so that at positions (0,1), (2,3), (4,5), etc., each pair follows the pattern where the second element is exactly double the first?

Example: [3,1,3,6] can be rearranged to [1,2,3,6] where 2=2*1 and 6=2*3, so return true.

Input & Output

example_1.py β€” Basic valid case
$ Input: [1,2,3,6]
β€Ί Output: true
πŸ’‘ Note: We can arrange as [1,2,3,6] where arr[1]=2=2Γ—arr[0]=2Γ—1 and arr[3]=6=2Γ—arr[2]=2Γ—3
example_2.py β€” Invalid case
$ Input: [3,1,3,6]
β€Ί Output: false
πŸ’‘ Note: We have two 3s but only one 6, so we cannot pair both 3s with their doubles
example_3.py β€” Negative numbers
$ Input: [4,-2,2,-4]
β€Ί Output: true
πŸ’‘ Note: We can arrange as [-2,-4,2,4] where -4=2Γ—(-2) and 4=2Γ—2

Constraints

  • 2 ≀ arr.length ≀ 3 Γ— 104
  • arr.length is even
  • -105 ≀ arr[i] ≀ 105
  • Note: Zero can pair with itself since 0 = 2 Γ— 0

Visualization

Tap to expand
Dance Partner Matching: Array of Doubled PairsExample: Heights [1, 2, 3, 6] - Can everyone pair up?1Height 12Height 2Pair!3Height 36Height 6Pair!Algorithm Steps:1. Count frequencies: {1:1, 2:1, 3:1, 6:1}2. Sort by value: [1, 2, 3, 6]3. For each height h, pair with height 2h4. βœ… Everyone paired successfully β†’ return true🎯 Key InsightProcess from smallest to largest absolute valuesThis greedy approach ensures optimal pairing without conflicts
Understanding the Visualization
1
Count Heights
Count how many dancers we have at each height
2
Sort by Height
Process dancers from shortest to tallest
3
Find Partners
For each height h, pair with dancers of height 2h
4
Check Success
Return true if everyone finds a partner
Key Takeaway
🎯 Key Insight: The greedy approach of pairing from smallest absolute values first guarantees that we find a valid arrangement if one exists, making this an optimal O(n log n) solution.
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
42.3K Views
Medium Frequency
~25 min Avg. Time
1.8K 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