Problem solution · Java

Final Array State After K Multiplication Operations II

Final Array State After K Multiplication Operations II: a Java solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
64 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeFinal Array State After K Multiplication Operations II · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int[] getFinalState(int[] nums, int k, int multiplier) {    if (multiplier == 1)      return nums;     final int n = nums.length;    final int maxNum = Arrays.stream(nums).max().getAsInt();    int[] ans = new int[n];    // (nums[i], i)    Queue<int[]> minHeap = new PriorityQueue<>(        Comparator.comparingInt((int[] a) -> a[0]).thenComparingInt((int[] a) -> a[1]));     for (int i = 0; i < n; ++i)      minHeap.offer(new int[] {nums[i], i});     // Keep multiplying the minimum number as close as possible to the maximum    // number in the array. After that, stop multiplying the minimum number    // because it will be greater than the maximum number in the array and break    // the circularity.    while (k > 0 && (long) minHeap.peek()[0] * multiplier <= maxNum) {      final int num = minHeap.peek()[0];      final int i = minHeap.poll()[1];      minHeap.offer(new int[] {num * multiplier, i});      --k;    }     List<int[]> sortedIndexedNums = new ArrayList<>(minHeap);    Collections.sort(sortedIndexedNums,                     Comparator.comparingInt((int[] sortedIndexedNum) -> sortedIndexedNum[0])                         .thenComparingInt((int[] sortedIndexedNum) -> sortedIndexedNum[1]));     final int multipliesPerNum = k / n;    final int remainingK = k % n;     // Evenly distribute the remaining multiplications to each number by using    // fast exponentiation.    for (int[] indexedNums : sortedIndexedNums)      indexedNums[0] = (int) ((long) indexedNums[0] * modPow(multiplier, multipliesPerNum) % MOD);     // Distribute the remaining multiplications to the minimum `remainingK`    // numbers.    for (int i = 0; i < remainingK; ++i)      sortedIndexedNums.get(i)[0] = (int) ((long) sortedIndexedNums.get(i)[0] * multiplier % MOD);     for (int[] indexedNums : sortedIndexedNums) {      final int num = indexedNums[0];      final int i = indexedNums[1];      ans[i] = num;    }     return ans;  }   private static final int MOD = 1_000_000_007;   private long modPow(long x, long n) {    if (n == 0)      return 1;    if (n % 2 == 1)      return x * modPow(x, n - 1) % MOD;    return modPow(x * x % MOD, n / 2);  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗