Knowledge Guide
HomeDSACompany Practice

medium Minimizing Array After Replacing Pairs With Their Product

Problem Statement

You are given an array containing integers nums and an integer value k. You can perform the below operation on the array elements for multiple times:

Return the minimum possible length of nums after performing multiple operations.

Examples

Try it yourself

Try solving this question here:

✅ Solution Minimizing Array After Replacing Pairs With Their Product

Problem Statement

You are given an array containing integers nums and an integer value k. You can perform the below operation on the array elements for multiple times:

  • Pick two adjacent elements, x and y, from nums and replace them with a single element equal to their product, x*y, but only if x*y is less than or equal to k.

Return the minimum possible length of nums after performing multiple operations.

Examples

  • Example 1:

    • Input: nums = [2, 3, 4, 5], k = 10
    • Expected Output: 3
    • Justification: We can replace 2 and 3 with their product 6 ([6, 4, 5]). No further operations can be performed since all adjacent products will exceed k. Hence, the minimum length is 3.
  • Example 2:

    • Input: nums = [1, 2, 2, 3], k = 5
    • Expected Output: 2
    • Justification: First, replace 2 and 2 with 4 ([1, 4, 3]), then replace 1 and 4 with 4 ([4, 3]). No more operations can be performed, resulting in a minimum length of 2.
  • Example 3:

    • Input: nums = [10, 5, 2, 3, 4, 2, 20, 1], k = 50
    • Expected Output: 3
    • Justification: First, replace 10 and 5 with 50 ([50, 2, 3, 4, 2, 20, 1]), then replace 2, 3, 4 and 2 with 48 ([50, 48, 20, 1]), and then replace 20 and 1 with 20 ([50, 48, 20]). No more operations can be performed, resulting in a minimum length of 3.

Solution

To solve this problem, we will iterate through the array and look for pairs of adjacent elements that can be replaced with their product without exceeding k. This process will be repeated until no more operations can be performed. The rationale behind this approach is to gradually reduce the array's length by merging elements that comply with the given condition, ensuring the final array is as short as possible. This method is efficient because it directly targets pairs that meet the condition and reduces the array size step by step, preventing unnecessary comparisons and operations.

We believe this approach will work because it iteratively consolidates adjacent elements under a clear condition, ensuring the array's length is minimized without overlooking any potential operations. By focusing on adjacent pairs, we take advantage of the problem's constraint on element selection, making the approach straightforward and effective in reaching the solution.

Step-by-Step Algorithm

  1. Initialization: Start by creating a dynamic list, res, to hold the potentially minimized array elements.

  2. Iterate Through Input Array: Loop through each element, num, in the given nums array.

    • Zero Check: If num equals 0, immediately return 1 as the minimum possible length because multiplying by zero will always meet the condition, and we can reduce the array to a single zero element.
  3. Check Last Element in res:

    • If res is not empty, check the product of the last element in res and num. If this product is less than or equal to k, it means we can combine these two numbers.
      • Combine: Update the last element in res with the product of the last element and num.
    • Else, if the product is greater than k or res is empty, append num to res.
  4. Continue Until End: Repeat steps 2 and 3 until you have processed all elements in the input nums array.

  5. Return Result: The length of res is the minimized length of the array. Return this length.

Algorithm Walkthrough

Let's consider the Input: nums = [10, 5, 2, 3, 4, 2, 20, 1], k = 50

  1. Initialization: Create an empty list res.

  2. First Element (10): res is empty, so add 10 to res. res becomes [10].

  3. Second Element (5): The product of 10 (last element in res) and 5 is 50, which is equal to k. Update the last element in res with this product. res becomes [50].

  4. Third Element (2): The product of 50 and 2 is 100, which is greater than k. Add 2 to res. res becomes [50, 2].

  5. Fourth Element (3): The product of 2 and 3 is 6, which is less than k. Combine these into 6. res becomes [50, 6].

  6. Fifth Element (4): The product of 6 and 4 is 24, which is less than k. Combine these into 24. res becomes [50, 24].

  7. Sixth Element (2): The product of 24 and 2 is 48, which is less than k. Combine these into 48. res becomes [50, 48].

  8. Seventh Element (20): The product of 48 and 20 is 960, which is greater than k. Add 20 to res. res becomes [50, 48, 20].

  9. Eighth Element (1): The product of 20 and 1 is 20, which is less than k. Combine these into 20. res becomes [50, 48, 20].

  10. End of Input Array: We've processed all elements in nums.

  11. Return Result: The length of res is 3. This is the minimum possible length of the array after performing the operations.

Code

java
import java.util.ArrayList;
import java.util.List;

public class Solution {

  // Minimizes the array by replacing pairs with their product
  public int minArrayLength(int[] nums, int k) {
    List<Integer> res = new ArrayList<>(); // Initialize a list to store the minimized array
    for (int num : nums) { // Iterate through the input array
      if (num == 0) { // If the current number is 0, the minimum array length is 1
        return 1;
      }
      if (!res.isEmpty() && res.get(res.size() - 1) * num <= k) { // If the product of last number and current number is less than or equal to k
        res.set(res.size() - 1, res.get(res.size() - 1) * num); // Update the last number in res to the product
      } else {
        res.add(num); // Otherwise, add the current number to res
      }
    }
    return res.size(); // Return the length of the minimized array
  }

  public static void main(String[] args) {
    Solution solution = new Solution();

    // Example 1
    int[] nums1 = { 2, 3, 4, 5 };
    int k1 = 10;
    System.out.println(solution.minArrayLength(nums1, k1)); // Output: 4

    // Example 2
    int[] nums2 = { 1, 2, 2, 3 };
    int k2 = 5;
    System.out.println(solution.minArrayLength(nums2, k2)); // Output: 2

    // Example 3
    int[] nums3 = { 10, 5, 2, 3, 4, 2, 20, 1 };
    int k3 = 50;
    System.out.println(solution.minArrayLength(nums3, k3)); // Output: 6
  }
}

Complexity Analysis

Time Complexity

  • The given algorithm iterates through the input array exactly once. For each element in the array, the operations performed (checking conditions, updating the list, and adding elements to the list) are constant time operations. Therefore, the time complexity is linear in the size of the input array, n, where n is the number of elements in the array.

Space Complexity

  • In the worst-case scenario, none of the adjacent elements can be combined (i.e., the product of any two adjacent elements always exceeds k). In this case, the algorithm will store all elements of the input array in the res list. Therefore, the space complexity is also linear in the size of the input array.
🤖 Don't fully get this? Learn it with Claude

Stuck on Minimizing Array After Replacing Pairs With Their Product? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Minimizing Array After Replacing Pairs With Their Product** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Minimizing Array After Replacing Pairs With Their Product** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Minimizing Array After Replacing Pairs With Their Product**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Minimizing Array After Replacing Pairs With Their Product**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes