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
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:
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
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.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code