Final Array State After K Multiplication Operations I

Apply k multiplications — each picks the smallest element (smallest index on ties) and multiplies it by m.

Easy
Time O(k log n) Space O(n)
LeetCode
5 min read
top-k heaps

Problem#

Each operation finds the smallest element (lowest index on ties) and multiplies it by multiplier. After k operations, return the array.

Examples#

  • nums = [2,1,3,5,6], k = 5, multiplier = 2[8,4,6,5,6]

Constraints#

  • 1 <= n <= 100, 1 <= k <= 10, 1 <= multiplier <= 5.

Approach#

Min-heap of (value, index). Pop, multiply, push.

Solution#

Final Array State After K Multiplications
class Solution {
public:
vector<int> getFinalState(vector<int>& nums, int k, int multiplier) {
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<>> pq;
for (int i = 0; i < (int)nums.size(); ++i) pq.push({nums[i], i});
while (k--) {
auto [v, i] = pq.top(); pq.pop();
nums[i] = v * multiplier;
pq.push({nums[i], i});
}
return nums;
}
};

Editorial#

Tuple (value, index) makes the heap order break ties by index automatically (smaller index has higher priority). Each operation is one pop + one push.

Complexity#

  • Time: O((n + k) log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.