Approach
Breadth-first search
For Final Array State After K Multiplication Operations II, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 64 lines of Java from the credited upstream file 3266.java.
- The implementation visibly relies on sequence storage, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] getFinalState(int[] nums, int k, int multiplier) {3 if (multiplier == 1)4 return nums;5 6 final int n = nums.length;7 final int maxNum = Arrays.stream(nums).max().getAsInt();8 int[] ans = new int[n];9 10 Queue<int[]> minHeap = new PriorityQueue<>(11 Comparator.comparingInt((int[] a) -> a[0]).thenComparingInt((int[] a) -> a[1]));12 13 for (int i = 0; i < n; ++i)14 minHeap.offer(new int[] {nums[i], i});15 16 17 18 19 20 while (k > 0 && (long) minHeap.peek()[0] * multiplier <= maxNum) {21 final int num = minHeap.peek()[0];22 final int i = minHeap.poll()[1];23 minHeap.offer(new int[] {num * multiplier, i});24 --k;25 }26 27 List<int[]> sortedIndexedNums = new ArrayList<>(minHeap);28 Collections.sort(sortedIndexedNums,29 Comparator.comparingInt((int[] sortedIndexedNum) -> sortedIndexedNum[0])30 .thenComparingInt((int[] sortedIndexedNum) -> sortedIndexedNum[1]));31 32 final int multipliesPerNum = k / n;33 final int remainingK = k % n;34 35 36 37 for (int[] indexedNums : sortedIndexedNums)38 indexedNums[0] = (int) ((long) indexedNums[0] * modPow(multiplier, multipliesPerNum) % MOD);39 40 41 42 for (int i = 0; i < remainingK; ++i)43 sortedIndexedNums.get(i)[0] = (int) ((long) sortedIndexedNums.get(i)[0] * multiplier % MOD);44 45 for (int[] indexedNums : sortedIndexedNums) {46 final int num = indexedNums[0];47 final int i = indexedNums[1];48 ans[i] = num;49 }50 51 return ans;52 }53 54 private static final int MOD = 1_000_000_007;55 56 private long modPow(long x, long n) {57 if (n == 0)58 return 1;59 if (n % 2 == 1)60 return x * modPow(x, n - 1) % MOD;61 return modPow(x * x % MOD, n / 2);62 }63}64