Array of Doubled Pairs — LeetCode 954 Python Solution
MediumGreedyArrayHash TableSorting
- Problem
- #954
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer array of even length arr, 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.
Example
- Input
- arr = [3,1,3,6]
- Output
- false
Python solution
Python
class Solution:
def canReorderDoubled(self, arr: List[int]) -> bool:
freq = Counter(arr)
if freq[0] & 1:
return False
for x in sorted(freq, key=abs):
if freq[x << 1] < freq[x]:
return False
freq[x << 1] -= freq[x]
return TrueComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 954. Array of Doubled Pairs is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 954. Array of Doubled Pairs?
- LeetCode 954. Array of Doubled Pairs is rated Medium on LeetCode.
- What is the time complexity of LeetCode 954. Array of Doubled Pairs?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 954. Array of Doubled Pairs?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 954. Array of Doubled Pairs cover?
- LeetCode 954. Array of Doubled Pairs is tagged Greedy, Array, Hash Table and Sorting on LeetCode.