You are given an integer array nums of length n. You may rearrange its elements to form any permutation perm.
Define an array power of length 15. For each 0 <= i < 15, power[i] is the largest integer j, where 0 <= j <= n, such that the first j elements of perm all have the (14 - i)th bit set.
Bit positions are indexed from right to left, starting with the 0th bit.
Return the lexicographically largest possible power array.
Example 1:
Input: nums = [7,5]
Output: [0,0,0,0,0,0,0,0,0,0,0,0,2,1,2]
Explanation:
Choose perm = [7, 5].
power[12] = 2.power[13] = 1.power[14] = 2.All higher bits are unset in the first element, so the remaining entries are 0.
Example 2:
Input: nums = [3,1,7]
Output: [0,0,0,0,0,0,0,0,0,0,0,0,1,2,3]
Explanation:
Choose perm = [7, 3, 1].
power[12] = 1.power[13] = 2.power[14] = 3.All higher bits are unset in the first element, so the remaining entries are 0.
Constraints:
1 <= nums.length <= 5 * 1040 <= nums[i] < 215When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To make the power array lexicographically largest, we must prioritize maximizing the power values corresponding to the most significant bits first. Sorting the input array in descending order naturally places numbers with the highest bits set at the front of the permutation. We then iterate through each bit position from most to least significant to count the length of the continuous prefix containing that bit.
Here's how the algorithm would work step-by-step:
def lexicographically_largest_power_array(nums: list[int]) -> list[int]:
# Sort the array in descending order to prioritize higher bits
sorted_numbers = sorted(nums, reverse=True)
power_result = [0] * 15
# Calculate the prefix length for each bit from 14 down to 0
for bit_index in range(15):
current_bit = 14 - bit_index
prefix_length = 0
# Count continuous elements from the start having current_bit set
for number in sorted_numbers:
if (number >> current_bit) & 1:
prefix_length += 1
else:
break
power_result[bit_index] = prefix_length
return power_result
The problem asks for the lexicographically largest power array of length 15, where each entry represents the length of the longest prefix of a permutation of nums that has a specific bit set. Because the prefix requirement means any element at index k must contain all bits whose required prefix length exceeds k, the required bitmasks for positions 0 through n - 1 form a decreasing sequence of subsets. We can greedily maximize each entry of the power array from index 0 to 14 by determining the maximum valid prefix length that can be supported by matching available numbers in nums.
Here's how the algorithm would work step-by-step:
def lexicographically_largest_power_array(nums: list[int]) -> list[int]:
# Count frequencies of each number in nums
total_elements = len(nums)
mask_counts = [0] * (1 << 15)
for number in nums:
mask_counts[number] += 1
# Compute superset sums for fast feasibility checking
for bit_index in range(15):
bit_mask = 1 << bit_index
for state in range((1 << 15) - 1, -1, -1):
if not (state & bit_mask):
mask_counts[state] += mask_counts[state | bit_mask]
power_result = [0] * 15
# Greedily determine each power value from bit 14 down to bit 0
for bit_position in range(15):
target_bit = 14 - bit_position
low_bound = 0
high_bound = total_elements
best_length = 0
while low_bound <= high_bound:
mid_candidate = (low_bound + high_bound) // 2
power_result[bit_position] = mid_candidate
# Check if current prefix lengths can be fulfilled
distinct_thresholds = sorted(list(set(power_result[:bit_position + 1] + [0, total_elements])))
is_feasible = True
for index in range(len(distinct_thresholds) - 1):
threshold_start = distinct_thresholds[index]
required_mask = 0
for checked_bit in range(bit_position + 1):
if power_result[checked_bit] > threshold_start:
required_mask |= (1 << (14 - checked_bit))
if mask_counts[required_mask] < power_result[checked_bit] if False else mask_counts[required_mask] < distinct_thresholds[index + 1]:
pass
# Validate using Hall's condition on nested intervals
for checked_index in range(bit_position + 1):
length_check = power_result[checked_index]
mask_check = 0
for other_bit in range(bit_position + 1):
if power_result[other_bit] >= length_check and length_check > 0:
mask_check |= (1 << (14 - other_bit))
if mask_counts[mask_check] < length_check:
is_feasible = False
break
if is_feasible:
best_length = mid_candidate
low_bound = mid_candidate + 1
else:
high_bound = mid_candidate - 1
power_result[bit_position] = best_length
return power_result
| Case | How to Handle |
|---|---|
| Empty input array or null input for either the array or allowed powers | Return an empty array immediately as no valid elements can be formed or selected. |
| Input array contains negative numbers, zeros, and extreme boundary values | Filter or process these values carefully against the allowed powers definition to prevent invalid mathematical operations like negative exponents. |
| Allowed powers set includes zero or one | Ensure the logic correctly handles base cases where raising values to the power of zero yields one or power of one yields the number itself without infinite loops. |
| All elements in the input array are identical | Group or count duplicates efficiently so that frequencies are preserved and sorted correctly to form the lexicographically largest result. |
| No elements in the input array can be formed using the allowed powers | Return an empty array since the filtering condition eliminates all candidate elements. |
| Maximum-sized inputs leading to large numerical values | Use appropriate data types and efficient sorting algorithms to prevent integer overflow and Time Limit Exceeded errors. |
| Multiple valid elements yield identical power combinations | Sort the qualifying elements in descending order to guarantee the resulting array is lexicographically as large as possible. |
| Large scale inputs with highly skewed distributions of valid power elements | Pre-compute or hash the valid power combinations to achieve fast membership lookup in O(1) average time per element. |