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
solution.c: In function ‘compare’
Line 15: Char 5: error: conversion to non-scalar type requested [solution.c]
18 | Element eb = (Element)b;
| ^~~~~~~
This error typically occurs when you attempt to cast a pointer to a non-scalar type directly rather than casting it to a pointer of that type. In C, you cannot cast a void* directly to a struct type; instead, you need to cast it to a pointer to that struct.
Correcting the compare Function
Assuming you have a structure Element defined as follows:
typedef struct {
int value;
int index; // To keep track of the original position if needed
} Element;
When implementing a compare function (for example, to use with qsort or a custom priority queue), you should cast the void* pointers to Element* pointers, not directly to Element. Here's how you can do it correctly:
int compare(const void *a, const void *b) {
const Element *ea = (const Element *)a;
const Element *eb = (const Element *)b;
if (ea->value < eb->value) return -1;
if (ea->value > eb->value) return 1;
return 0;
}
Explanation:
Casting Pointers Correctly:
a and b are of type const void *.
Cast them to const Element * (note the asterisk *) to obtain pointers to Element structures.
Comparing Values:
Compare the value fields of the two Element structures.
Return -1, 1, or 0 based on the comparison, as required by functions like qsort.
Implementing the Solution in C
Given the constraints of the problem (especially k can be up to (10^9)), implementing an efficient solution in C can be challenging. C doesn't have a built-in priority queue, so you'd need to implement a heap manually or use another strategy.
However, I'll outline an approach that can be efficient enough, assuming you implement an efficient heap:
Step-by-Step Approach
Use a Min Heap:
Store each element along with its index to handle duplicates (to always pick the first occurrence).
Implement a min heap based on the value. If there's a tie, prioritize the element with the smaller index.
Perform Multiplication Operations:
For each of the k operations:
Extract the minimum element.
Multiply its value by the multiplier.
Push the updated element back into the heap.
Apply Modulo Operation:
After all operations, iterate through the array and apply value % (10^9 + 7) to each element.
Sample Implementation Snippet
I'll provide a simplified version of how you might structure your C code. Note that implementing a full-fledged heap is beyond the scope of this answer, but I'll guide you through the essential parts.
#include <stdio.h>
#include <stdlib.h>
#define MOD 1000000007
typedef struct {
long long value;
int index;
} Element;
// Comparator function for qsort (min heap)
int compare(const void *a, const void *b) {
const Element *ea = (const Element *)a;
const Element *eb = (const Element *)b;
if (ea->value < eb->value) return -1;
if (ea->value > eb->value) return 1;
if (ea->index < eb->index) return -1;
if (ea->index > eb->index) return 1;
return 0;
}
// Function to simulate k operations
int* getFinalState(int* nums, int numsSize, int k, int multiplier, int* returnSize) {
Element *elements = (Element *)malloc(numsSize * sizeof(Element));
for(int i = 0; i < numsSize; i++) {
elements[i].value = nums[i];
elements[i].index = i;
}
// Sort the elements initially
qsort(elements, numsSize, sizeof(Element), compare);
// Perform k operations
for(int i = 0; i < k; i++) {
// Always modify the first element since it's the smallest
elements[0].value *= (long long)multiplier;
// Re-sort to maintain the heap property
// In a real heap, you'd perform a heapify-right or similar operation
qsort(elements, numsSize, sizeof(Element), compare);
}
// Prepare the result
int *result = (int *)malloc(numsSize * sizeof(int));
for(int i = 0; i < numsSize; i++) {
result[elements[i].index] = (int)(elements[i].value % MOD);
}
*returnSize = numsSize;
free(elements);
return result;
}
Notes:
Efficiency Considerations:
This implementation uses qsort after every multiplication operation, which is inefficient for large k (up to (10^9)). To handle large k, you'd need a more efficient heap implementation (like a binary heap) with O(log n) per operation instead of O(n log n) with qsort.
Implementing a Heap:
To achieve better performance, implement a min heap manually using an array. This allows inserting and extracting the minimum element in O(log n) time.
For very large k, consider mathematical optimizations or patterns where elements stabilize and stop changing order after multiple multiplications.
Recommended Steps
Implement a Min Heap:
Use an array to represent the heap.
Implement push and pop operations with appropriate bubbling up and down.
Optimize Multiplications:
If the same element remains the smallest for multiple consecutive operations, calculate how many times it will be multiplied before the next element becomes smaller.
Apply Modulo at the End:
Since intermediate values can be very large, apply modulo operations as needed to prevent integer overflow.
Example of Correct compare Function
Here's a complete example of a correct compare function within a min heap context:
int compare(const void *a, const void *b) {
const Element *ea = (const Element *)a;
const Element *eb = (const Element *)b;
if (ea->value != eb->value)
return (ea->value < eb->value) ? -1 : 1;
else
return (ea->index < eb->index) ? -1 : 1;
}
However, as previously mentioned, for performance reasons, implementing a heap is preferable for handling k operations efficiently.
Alternative Approach: Using Priority Queue Libraries
If you're open to using additional libraries, consider leveraging existing priority queue implementations in C to save time and ensure efficiency. Libraries like glib provide priority queue functionalities that you can utilize.
Final Recommendations
Implement Efficient Data Structures:
For handling large inputs and operations efficiently, invest time in implementing or using efficient data structures like heaps.
Handle Large k Smartly:
Look for mathematical patterns or optimizations that allow you to reduce the number of operations, especially when k is very large.
Test with Small Inputs First:
Before scaling up, ensure your implementation works correctly with smaller inputs and a smaller number of operations.
Consider Other Languages for Simplicity:
If C proves too cumbersome for this problem, languages like C++ offer built-in priority queues (std::priority_queue) which can simplify your implementation.
Example in C++ (For Reference)
If you consider using C++, here's how you might implement the solution more efficiently:
#include <vector>
#include <queue>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
struct Element {
ll value;
int index;
bool operator<(const Element& other) const {
if (value == other.value)
return index > other.index; // Min heap based on index if values are equal
return value > other.value; // Min heap based on value
}
};
vector<int> getFinalState(vector<int>& nums, long long k, int multiplier) {
int n = nums.size();
priority_queue<Element> pq;
for(int i = 0; i < n; i++) {
pq.push(Element{(ll)nums[i], i});
}
while(k > 0) {
Element current = pq.top(); pq.pop();
current.value *= multiplier;
pq.push(current);
k--;
}
// Extract final values
vector<int> result(n);
while(!pq.empty()){
Element current = pq.top(); pq.pop();
result[current.index] = current.value % MOD;
}
return result;
}
This C++ example uses a priority queue to efficiently perform the k operations.
I hope this helps you resolve the compilation error and guides you toward implementing an efficient solution for the problem. If you have specific parts of your C code you'd like further assistance with, feel free to share them!