Leetcode 954: Array of Doubled Pairs

grid47
grid47
Exploring patterns and algorithms
Aug 3, 2024 6 min read

Given an integer array of even length, determine if it is possible to reorder the array such that for every index i, arr[2 * i + 1] = 2 * arr[2 * i] holds true. If it is possible to reorder the array in this way, return true, otherwise return false.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of integers, arr, with even length.
Example: Input: arr = [6, 3, 4, 8]
Constraints:
• 2 <= arr.length <= 30000
• arr.length is even.
• -105 <= arr[i] <= 105
Output: The output should be a boolean value: true if the array can be reordered as described, false otherwise.
Example: Output: true
Constraints:
• The output will be a boolean indicating if the array can be reordered accordingly.
Goal: The goal is to check whether we can reorder the elements in pairs such that each second element is twice the first element.
Steps:
• 1. Create a frequency map to count occurrences of each element.
• 2. Sort the unique elements by their absolute values.
• 3. For each element, check if the frequency of its double exists. If not, return false.
• 4. Adjust the frequencies accordingly after each pair is formed.
• 5. If all elements are successfully paired, return true; otherwise, return false.
Goal: The input array will always have an even length, and the solution must handle arrays of size up to 30000 efficiently.
Steps:
• The input array length is always even.
• The array elements are in the range [-105, 105].
• The array will contain unique integers.
Assumptions:
• The array will always have an even number of elements.
• We assume the input array is non-empty.
Input: Input: arr = [6, 3, 4, 8]
Explanation: In this case, we cannot reorder the array such that for every i, arr[2 * i + 1] = 2 * arr[2 * i] because the elements do not form valid pairs.

Input: Input: arr = [4, -2, 2, -4]
Explanation: Here, we can form pairs [-2, -4] and [2, 4], so the array can be reordered to form a valid sequence.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus