Taro Logo

Lexicographically Largest Power Array

#8 Most AskedHard
0 views
Topics:
ArraysGreedy AlgorithmsBit Manipulation

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].

  • Both elements have bit 2 set, so power[12] = 2.
  • The first element has bit 1 set, but the second does not, so power[13] = 1.
  • Both elements have bit 0 set, so 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].

  • The first element has bit 2 set, but the second does not, so power[12] = 1.
  • The first two elements have bit 1 set, but the third does not, so power[13] = 2.
  • All three elements have bit 0 set, so power[14] = 3.

All higher bits are unset in the first element, so the remaining entries are 0.

Constraints:

  • 1 <= nums.length <= 5 * 104
  • 0 <= nums[i] < 215

Solution


Clarifying Questions

When 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:

  1. What specifically does 'combinations of these powers' mean in this context (e.g., can we use addition, multiplication, or raise elements to these powers), and are the powers applied to the array elements or are we choosing numbers that equal a sum of these powers?
  2. How are the allowed integer powers provided (e.g., as a list of exponents, or as a set of pre-calculated base-power values), and can each power be used multiple times or only once?
  3. Can the input array contain negative numbers, zeros, or duplicates, and do duplicates affect the count or availability of elements we can select?
  4. What should be returned if no elements from the input array can satisfy the condition of being expressed via the allowed powers?
  5. Is the size of the resulting array fixed, or should we select the maximum possible subset of valid elements that forms the lexicographically largest arrangement?

Brute Force Solution

Approach

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:

  1. Sort the given list of numbers in descending order to form the optimal permutation.
  2. Initialize an array of size 15 with zeros to store the resulting power values.
  3. Iterate over each index from 0 to 14, computing the corresponding bit position 14 - index.
  4. Count how many elements from the beginning of the sorted array have that bit set before encountering an element without it.
  5. Store the prefix length in the power array and return the result.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n log n) – Sorting the array of size n takes O(n log n) time. Computing the prefix lengths takes at most 15 * n operations, which is O(n). Thus, the total time complexity is dominated by O(n log n).
Space Complexity
O(n) – Creating the sorted copy of the input list requires O(n) auxiliary space, while the output array has a fixed size of 15.

Optimal Solution

Approach

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:

  1. Precompute the frequency of each bitmask present in nums up to 15 bits.
  2. Iterate through each bit from 14 down to 0, which corresponds to indices 0 through 14 of the power array.
  3. For the current bit, binary search or find the maximum prefix length such that a valid assignment of numbers in nums to the required nested bitmasks remains possible.
  4. Validate feasibility of a candidate configuration by verifying that for every subset of required bits, there are enough numbers in nums that are supersets of the required mask.
  5. Record the optimal length for the current bit and return the resulting 15-element power array.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(B * 2^B + B^2 * log(N)) – Computing the SOS DP (superset sums) takes O(B * 2^B) where B = 15. Then for each of the 15 bit positions, we perform a binary search over [0, N], taking O(log N) iterations with O(B) mask evaluations per iteration.
Space Complexity
O(2^B) – An array of size 2^15 = 32768 is allocated to store the frequencies and SOS DP counts for all 15-bit integers.

Edge Cases

Empty input array or null input for either the array or allowed powers
How to Handle:
Return an empty array immediately as no valid elements can be formed or selected.
Input array contains negative numbers, zeros, and extreme boundary values
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Return an empty array since the filtering condition eliminates all candidate elements.
Maximum-sized inputs leading to large numerical values
How to Handle:
Use appropriate data types and efficient sorting algorithms to prevent integer overflow and Time Limit Exceeded errors.
Multiple valid elements yield identical power combinations
How to Handle:
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
How to Handle:
Pre-compute or hash the valid power combinations to achieve fast membership lookup in O(1) average time per element.
0/38 completed