Run
Description
Editorial
Editorial
Solutions
Solutions
Submissions
Submissions
Code
Testcase
Testcase
Test Result
3266. Final Array State After K Multiplication Operations II
Attempted
Hard
Topics
Companies
Hint
You are given an integer array nums, an integer k, and an integer multiplier.
You need to perform k operations on nums. In each operation:
Find the minimum value x in nums. If there are multiple occurrences of the minimum value, select the one that appears first.
Replace the selected minimum value x with x * multiplier.
After the k operations, apply modulo 109 + 7 to every value in nums.
Return an integer array denoting the final state of nums after performing all k operations and then applying the modulo.
Example 1:
Input: nums = [2,1,3,5,6], k = 5, multiplier = 2
Output: [8,4,6,5,6]
Explanation:
Operation Result
After operation 1 [2, 2, 3, 5, 6]
After operation 2 [4, 2, 3, 5, 6]
After operation 3 [4, 4, 3, 5, 6]
After operation 4 [4, 4, 6, 5, 6]
After operation 5 [8, 4, 6, 5, 6]
After applying modulo [8, 4, 6, 5, 6]
Example 2:
Input: nums = [100000,2000], k = 2, multiplier = 1000000
Output: [999999307,999999993]
Explanation:
Operation Result
After operation 1 [100000, 2000000000]
After operation 2 [100000000000, 2000000000]
After applying modulo [999999307, 999999993]
Seen this question in a real interview before?
1/5
Yes
No
Accepted
6.3K
Submissions
63.7K
Acceptance Rate
9.8%
Topics
Companies
Hint 1
Hint 2
Hint 3
Discussion (39)
Note: The returned array must be malloced, assume caller calls free().
/
int getFinalState(int nums, int numsSize, int k, int multiplier, int returnSize) {
}
Saved
Compile Error
solution.c: In function ‘compare’
Line 15: Char 5: error: conversion to non-scalar type requested [solution.c]
18 | Element eb = (Element)b;
| ^~~~~~~
Problem List
Tag
3266. Final Array State After K Multiplication Operations II
Hard
ArrayHeap (Priority Queue)Simulation
3276. Select Cells in Grid With Maximum Score
Hard
ArrayDynamic ProgrammingBit ManipulationMatrix1+
420. Strong Password Checker
Hard
StringGreedyHeap (Priority Queue)
3245. Alternating Groups III
Hard
ArrayBinary Indexed Tree
3161. Block Placement Queries
Hard
ArrayBinary SearchBinary Indexed TreeSegment Tree
3256. Maximum Value Sum by Placing Three Rooks I
Hard
Assistant
ArrayDynamic ProgrammingMatrixEnumeration
3260. Find the Largest Palindrome Divisible by K
Hard
MathStringDynamic ProgrammingGreedy1+
3234. Count the Number of Substrings With Dominant Ones
Med.
StringSliding WindowEnumeration
2945. Find Maximum Non-decreasing Array Length
Hard
ArrayBinary SearchDynamic ProgrammingStack3+
2612. Minimum Reverse Operations
Hard
ArrayBreadth-First SearchOrdered Set
3139. Minimum Cost to Equalize Array
Hard
ArrayGreedyEnumeration
3116. Kth Smallest Amount With Single Denomination Combination
Hard
ArrayMathBinary SearchBit Manipulation2+
3165. Maximum Sum of Subsequence With Non-adjacent Elements
Hard
ArrayDivide and ConquerDynamic ProgrammingSegment Tree
2423. Remove Letter To Equalize Frequency
Easy
Hash TableStringCounting
1622. Fancy Sequence
Hard
MathDesignSegment Tree
29. Divide Two Integers
Med.
MathBit Manipulation
8. String to Integer (atoi)
Med.
String
2286. Booking Concert Tickets in Groups
Hard
Binary SearchDesignBinary Indexed TreeSegment Tree
2827. Number of Beautiful Integers in the Range
Hard
MathDynamic Programming
3026. Maximum Good Subarray Sum
Med.
ArrayHash TablePrefix Sum
2591. Distribute Money to Maximum Children
Easy
MathGreedy
3213. Construct String with Minimum Cost
Hard
ArrayStringDynamic ProgrammingSuffix Array
65. Valid Number
Hard
String
3267. Count Almost Equal Pairs II
Hard
ArrayHash TableSortingCounting1+
2790. Maximum Number of Groups With Increasing Length
Hard
ArrayMathBinary SearchGreedy1+
2035. Partition Array Into Two Arrays to Minimize Sum Difference
Hard
ArrayTwo PointersBinary SearchDynamic Programming3+
3261. Count Substrings That Satisfy K-Constraint II
Hard
ArrayStringBinary SearchSliding Window1+
1977. Number of Ways to Separate Numbers
Hard
StringDynamic ProgrammingSuffix Array
3181. Maximum Total Reward Using Operations II
Hard
ArrayDynamic ProgrammingBit Manipulation
3001. Minimum Moves to Capture The Queen
Med.
ArrayEnumeration
2902. Count of Sub-Multisets With Bounded Sum
Hard
ArrayHash TableDynamic ProgrammingSliding Window
2916. Subarrays Distinct Element Sum of Squares II
Hard
ArrayDynamic ProgrammingBinary Indexed TreeSegment Tree
3017. Count the Number of Houses at a Certain Distance II
Hard
GraphPrefix Sum
2289. Steps to Make Array Non-decreasing
Med.
ArrayLinked ListStackMonotonic Stack
2967. Minimum Cost to Make Array Equalindromic
Med.
ArrayMathBinary SearchGreedy1+
3251. Find the Count of Monotonic Pairs II
Hard
ArrayMathDynamic ProgrammingCombinatorics1+
3049. Earliest Second to Mark Indices II
Hard
ArrayBinary SearchGreedyHeap (Priority Queue)
220. Contains Duplicate III
Hard
ArraySliding WindowSortingBucket Sort1+
3240. Minimum Number of Flips to Make Binary Grid Palindromic II
Med.
ArrayTwo PointersMatrix
3224. Minimum Array Changes to Make Differences Equal
Med.
ArrayHash TablePrefix Sum
2856. Minimum Array Length After Pair Removals
Med.
ArrayHash TableTwo PointersBinary Search2+
2202. Maximize the Topmost Element After K Moves
Med.
ArrayGreedy
3149. Find the Minimum Cost Array Permutation
Hard
ArrayDynamic ProgrammingBit ManipulationBitmask
2975. Maximum Square Area by Removing Fences From a Field
Med.
ArrayHash TableEnumeration
2584. Split the Array to Make Coprime Products
Hard
ArrayHash TableMathNumber Theory
2572. Count the Number of Square-Free Subsets
Med.
ArrayMathDynamic ProgrammingBit Manipulation1+
3086. Minimum Moves to Pick K Ones
Hard
ArrayGreedySliding WindowPrefix Sum
3244. Shortest Distance After Road Addition Queries II
Hard
ArrayGreedyGraphOrdered Set
2156. Find Substring With Given Hash Value
Hard
StringSliding WindowRolling HashHash Function
3241. Time Taken to Mark All Nodes
Hard
Dynamic ProgrammingTreeDepth-First SearchGraph
1191. K-Concatenation Maximum Sum
Med.
ArrayDynamic Programming
2926. Maximum Balanced Subsequence Sum
Hard
ArrayBinary SearchDynamic ProgrammingBinary Indexed Tree1+
2407. Longest Increasing Subsequence II
Hard
ArrayDivide and ConquerDynamic ProgrammingBinary Indexed Tree3+
3177. Find the Maximum Length of a Good Subsequence II
Hard
ArrayHash TableDynamic Programming
2708. Maximum Strength of a Group
Med.
ArrayDynamic ProgrammingBacktrackingGreedy3+
3098. Find the Sum of Subsequence Powers
Hard
ArrayDynamic ProgrammingSorting
3008. Find Beautiful Indices in the Given Array II
Hard
Two PointersStringBinary SearchRolling Hash2+
3020. Find the Maximum Number of Elements in Subset
Med.
ArrayGraphTopological Sort
3196. Maximize Total Cost of Alternating Subarrays
Med.
ArrayDynamic Programming
44. Wildcard Matching
Hard
StringDynamic ProgrammingGreedyRecursion
2569. Handling Sum Queries After Update
Hard
ArraySegment Tree
3272. Find the Count of Good Integers
Hard
Hash TableMathCombinatoricsEnumeration
2741. Special Permutations
Med.
ArrayDynamic ProgrammingBit ManipulationBitmask
3134. Find the Median of the Uniqueness Array
Hard
ArrayHash TableBinary SearchSliding Window
2029. Stone Game IX
Med.
ArrayMathGreedyCounting1+
605. Can Place Flowers
Easy
ArrayGreedy
1862. Sum of Floored Pairs
Hard
ArrayMathBinary SearchPrefix Sum
2040. Kth Smallest Product of Two Sorted Arrays
Hard
ArrayBinary Search
7. Reverse Integer
Med.
Math
2736. Maximum Sum Queries
Hard
ArrayBinary SearchStackBinary Indexed Tree3+
1590. Make Sum Divisible by P
Med.
ArrayHash TablePrefix Sum
2047. Number of Valid Words in a Sentence
Easy
String
1494. Parallel Courses II
Hard
Dynamic ProgrammingBit ManipulationGraphBitmask
3180. Maximum Total Reward Using Operations I
Med.
ArrayDynamic Programming
2183. Count Array Pairs Divisible by K
Hard
ArrayMathNumber Theory
2842. Count K-Subsequences of a String With Maximum Beauty
Hard
Hash TableMathStringGreedy1+
1654. Minimum Jumps to Reach Home
Med.
ArrayDynamic ProgrammingBreadth-First Search
2234. Maximum Total Beauty of the Gardens
Hard
ArrayTwo PointersBinary SearchGreedy1+
2771. Longest Non-decreasing Subarray From Two Arrays
Med.
ArrayDynamic Programming
464. Can I Win
Med.
MathDynamic ProgrammingBit ManipulationMemoization2+
Paramètres concernant la confidentialité et les cookies
Géré par Google. Conforme au TCF de l'IAB. ID de CMP : 300
To solve LeetCode Problem 3266: Final Array State After K Multiplication Operations II, it's essential to handle the large constraints efficiently, especially since k can be as large as (10^9) and nums.length up to (10^4). Simulating each operation individually would be computationally infeasible. Instead, we'll adopt a bulk processing strategy to apply multiple operations in one step wherever possible.
Problem Summary
Given:
An integer array nums
Integers k and multiplier
Operation:
Find the minimum value x in nums (select the first occurrence if multiple).
Replace x with x * multiplier.
Goal:
After performing k operations, return the final state of nums, with each element taken modulo (10^9 + 7).
Efficient Approach
Sort the Elements:
Sort the array while keeping track of their original indices. This allows us to efficiently determine which elements to multiply next.
Bulk Operations:
Iterate through the sorted array and determine how many times you can multiply a group of minimum elements before they exceed the next unique value in the sorted list.
This reduces the number of operations by handling multiple multiplications in one step.
Binary Search for Multiplications:
For each group of elements with the same value, use binary search to find the maximum number of multiplications (t) that can be applied without exceeding the next unique value in the array.
Multiply the group's elements by multiplier^t and reduce k accordingly.
Handle Remaining Operations:
If there are leftover operations (k), distribute them one by one to the smallest elements.
Apply Modulo:
After all multiplications, apply modulo (10^9 + 7) to each element to obtain the final array state.
Implementation in C
Below is a C implementation of the above approach. It includes detailed comments to help you understand each step. Note that due to the complexity of handling large exponents and avoiding overflow, the code uses unsigned long long for intermediate calculations.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MOD 1000000007
typedef struct {
long long value;
int index;
} Element;
// Comparison function for qsort
int compare_elements(const void* a, const void* b) {
Element* ea = (Element*)a;
Element* eb = (Element*)b;
if (ea->value != eb->value)
return (ea->value < eb->value) ? -1 : 1;
return ea->index - eb->index;
}
// Function to calculate multiplier^t without overflow, returns -1 if overflow occurs
long long power_with_limit(long long base, int t, long long limit) {
long long result = 1;
for(int i = 0; i < t; i++){
if (result > limit / base) return -1; // Indicates overflow beyond limit
result *= base;
}
return result;
}
int* getFinalState(int* nums, int numsSize, int k, int multiplier, int* returnSize){
// Create an array of Elements with value and original index
Element* elements = (Element*)malloc(sizeof(Element) * numsSize);
for(int i = 0; i < numsSize; i++){
elements[i].value = nums[i];
elements[i].index = i;
}
// Sort the elements by value ascendingly
qsort(elements, numsSize, sizeof(Element), compare_elements);
// Array to store the number of times each element is multiplied
long long* multiply_counts = (long long*)calloc(numsSize, sizeof(long long));
int current_group = 0;
while(current_group < numsSize && k > 0){
// Find the size of the current group (elements with the same value)
int group_start = current_group;
long long current_val = elements[current_group].value;
int group_size = 1;
while(current_group + group_size < numsSize && elements[current_group + group_size].value == current_val){
group_size++;
}
// Determine the next distinct value
if(current_group + group_size < numsSize){
long long next_val = elements[current_group + group_size].value;
// Find the maximum t such that current_val * multiplier^t < next_val
// We use binary search to find t
int low = 1;
int high = 60; // Because multiplier^60 is already very large
int t = 0;
while(low <= high){
int mid = low + (high - low)/2;
long long potential = power_with_limit(multiplier, mid, next_val -1);
if(potential == -1){
high = mid -1;
}
else{
double power = pow((double)multiplier, mid);
if(current_val * power < (double)next_val){
t = mid;
low = mid +1;
}
else{
high = mid -1;
}
}
}
// Total operations needed to apply t multiplications to the group
long long total_ops = (long long)t * group_size;
if(total_ops <= k){
// Apply t multiplications to each element in the group
for(int i = group_start; i < group_start + group_size; i++){
multiply_counts[i] += t;
}
k -= total_ops;
current_group += group_size;
}
else{
// Calculate the maximum t we can apply
long long possible_t = k / group_size;
if(possible_t >0){
for(int i = group_start; i < group_start + group_size; i++){
multiply_counts[i] += possible_t;
}
k -= possible_t * group_size;
}
// Now distribute the remaining k operations one by one
if(k >0){
for(int i = group_start; i < group_start + group_size && k >0; i++, k--){
multiply_counts[i]++;
}
}
break; // All operations are done
}
}
else{
// Last group, apply as many multiplications as possible
long long t = k / group_size;
if(t >0){
for(int i = current_group; i < numsSize; i++){
multiply_counts[i] += t;
}
k -= t * group_size;
}
// Distribute remaining k operations one by one
if(k >0){
for(int i = current_group; i < numsSize && k >0; i++, k--){
multiply_counts[i]++;
}
}
break; // All operations are done
}
}
// Prepare the result array
int* result = (int*)malloc(sizeof(int) * numsSize);
for(int i = 0; i < numsSize; i++){
// Calculate the final value with multiplier^multiply_counts[i]
long long final_val = elements[i].value;
if(multiply_counts[i] >0){
// To avoid overflow, calculate power modulo MOD
long long temp = 1;
for(int t =0; t < multiply_counts[i]; t++){
temp = (temp * (long long)multiplier) % MOD;
// If temp becomes 0, no need to continue
if(temp ==0) break;
}
final_val = (final_val * temp) % MOD;
}
else{
final_val %= MOD;
}
result[elements[i].index] = (int)(final_val);
}
*returnSize = numsSize;
// Free allocated memory
free(elements);
free(multiply_counts);
return result;
}
// Example usage
int main(){
int nums[] = {2,1,3,5,6};
int numsSize = 5;
int k =5;
int multiplier = 2;
int returnSize;
int* final_state = getFinalState(nums, numsSize, k, multiplier, &returnSize);
for(int i =0; i < returnSize; i++) printf("%d ", final_state[i]);
printf("\n");
free(final_state);
return 0;
}
Explanation of the Code
Struct Element:
Holds both the value of an element and its original index to map back after sorting.
Sorting:
The array is sorted based on the values to efficiently identify groups of identical elements.
Bulk Multiplications:
For each group of identical elements, determine how many times (t) they can be multiplied by multiplier before exceeding the next distinct value.
Use binary search to find the maximum feasible t without overflow.
Apply t multiplications to the entire group if possible, updating k accordingly.
If not enough k remains to fully apply t, distribute the remaining operations individually.
Final Calculations:
After determining how many times each element should be multiplied, compute the final value.
To handle large exponents and prevent overflow, calculate the multiplications modulo (10^9 + 7).
Restoring Original Order:
The final values are placed back into their original positions using the stored indices.
Memory Management:
Allocate and free memory appropriately to prevent leaks, especially important in C.
Handling Compile Errors
The compile error you encountered was:
solution.c: In function ‘compare’
Line 15: Char 5: error: conversion to non-scalar type requested [solution.c]
18 | Element eb = (Element)b;
| ^~~~~~~
This occurs because you're attempting to cast a void* directly to Element instead of Element*. In C, when using qsort, the comparison function receives const void* pointers to the elements. You need to cast them to pointers to the correct type and then dereference them to access their fields.
Corrected compare_elements Function:
int compare_elements(const void* a, const void* b) {
Element* ea = (Element*)a;
Element* eb = (Element*)b;
if (ea->value != eb->value)
return (ea->value < eb->value) ? -1 : 1;
return ea->index - eb->index;
}
Key Points:
Cast a and b to Element* before dereferencing.
Return -1, 0, or 1 based on the comparison.
Testing the Solution
The provided main function tests the solution with the first example:
int nums[] = {2,1,3,5,6};
int numsSize = 5;
int k =5;
int multiplier = 2;
Expected Output:
8 4 6 5 6
This matches the example provided in the problem statement.
Conclusion
By adopting a bulk processing approach and efficiently determining how many operations can be applied to each group of elements, we can handle the large constraints of this problem. The key is to minimize the number of iterations over k by applying as many operations as possible in each step, ensuring the solution remains efficient even for large inputs.