Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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 1:
Input: arr = [3,1,3,6] Output: false
Example 2:
Input: arr = [2,1,2,6] Output: false
Example 3:
Input: arr = [4,-2,2,-4] Output: true Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].
Constraints:
2 <= arr.length <= 3 * 104arr.length is even.-105 <= arr[i] <= 105Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Greedy
[3,1,3,6]
[2,1,2,6]
[4,-2,2,-4]
find-original-array-from-doubled-array)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #954: Array of Doubled Pairs
class Solution {
public boolean canReorderDoubled(int[] arr) {
Map<Integer, Integer> freq = new HashMap<>();
for (int v : arr) {
freq.put(v, freq.getOrDefault(v, 0) + 1);
}
if ((freq.getOrDefault(0, 0) & 1) != 0) {
return false;
}
List<Integer> keys = new ArrayList<>(freq.keySet());
keys.sort(Comparator.comparingInt(Math::abs));
for (int k : keys) {
if (freq.getOrDefault(k << 1, 0) < freq.get(k)) {
return false;
}
freq.put(k << 1, freq.getOrDefault(k << 1, 0) - freq.get(k));
}
return true;
}
}
// Accepted solution for LeetCode #954: Array of Doubled Pairs
func canReorderDoubled(arr []int) bool {
freq := make(map[int]int)
for _, v := range arr {
freq[v]++
}
if freq[0]%2 != 0 {
return false
}
var keys []int
for k := range freq {
keys = append(keys, k)
}
sort.Slice(keys, func(i, j int) bool {
return abs(keys[i]) < abs(keys[j])
})
for _, k := range keys {
if freq[k*2] < freq[k] {
return false
}
freq[k*2] -= freq[k]
}
return true
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #954: Array of Doubled Pairs
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 True
// Accepted solution for LeetCode #954: Array of Doubled Pairs
struct Solution;
use std::cmp::Ordering::*;
impl Solution {
fn can_reorder_doubled(a: Vec<i32>) -> bool {
let mut nonzero: Vec<Vec<i32>> = vec![vec![]; 2];
let mut zero: usize = 0;
for x in a {
match x.cmp(&0) {
Equal => {
zero += 1;
}
Less => {
nonzero[0].push(-x);
}
Greater => {
nonzero[1].push(x);
}
}
}
if zero % 2 != 0 || nonzero[0].len() % 2 != 0 || nonzero[1].len() % 2 != 0 {
return false;
}
for i in 0..2 {
nonzero[i].sort_unstable();
let size = nonzero[i].len();
let mut fast = 0;
for slow in 0..size {
if nonzero[i][slow] == 0 {
continue;
} else {
while fast < size && nonzero[i][fast] != 2 * nonzero[i][slow] {
fast += 1;
}
if fast == size {
return false;
} else {
nonzero[i][fast] = 0;
}
}
}
}
true
}
}
#[test]
fn test() {
let a = vec![3, 1, 3, 6];
let res = false;
assert_eq!(Solution::can_reorder_doubled(a), res);
let a = vec![2, 1, 2, 6];
let res = false;
assert_eq!(Solution::can_reorder_doubled(a), res);
let a = vec![4, -2, 2, -4];
let res = true;
assert_eq!(Solution::can_reorder_doubled(a), res);
let a = vec![1, 2, 4, 16, 8, 4];
let res = false;
assert_eq!(Solution::can_reorder_doubled(a), res);
let a = vec![1, 2, 1, -8, 8, -4, 4, -4, 2, -2];
let res = true;
assert_eq!(Solution::can_reorder_doubled(a), res);
}
// Accepted solution for LeetCode #954: Array of Doubled Pairs
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #954: Array of Doubled Pairs
// class Solution {
// public boolean canReorderDoubled(int[] arr) {
// Map<Integer, Integer> freq = new HashMap<>();
// for (int v : arr) {
// freq.put(v, freq.getOrDefault(v, 0) + 1);
// }
// if ((freq.getOrDefault(0, 0) & 1) != 0) {
// return false;
// }
// List<Integer> keys = new ArrayList<>(freq.keySet());
// keys.sort(Comparator.comparingInt(Math::abs));
// for (int k : keys) {
// if (freq.getOrDefault(k << 1, 0) < freq.get(k)) {
// return false;
// }
// freq.put(k << 1, freq.getOrDefault(k << 1, 0) - freq.get(k));
// }
// return true;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.