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:
- Pick two adjacent elements,
xandy, fromnumsand replace them with a single element equal to their product,x*y, but only ifx*yis less than or equal tok.
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 exceedk. Hence, the minimum length is3.
- Input:
-
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 of2.
- Input:
-
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 of3.
- Input:
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,
xandy, fromnumsand replace them with a single element equal to their product,x*y, but only ifx*yis less than or equal tok.
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 exceedk. Hence, the minimum length is3.
- Input:
-
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 of2.
- Input:
-
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 of3.
- Input:
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
-
Initialization: Start by creating a dynamic list,
res, to hold the potentially minimized array elements. -
Iterate Through Input Array: Loop through each element,
num, in the givennumsarray.- Zero Check: If
numequals0, immediately return1as the minimum possible length because multiplying by zero will always meet the condition, and we can reduce the array to a single zero element.
- Zero Check: If
-
Check Last Element in
res:- If
resis not empty, check the product of the last element inresandnum. If this product is less than or equal tok, it means we can combine these two numbers.- Combine: Update the last element in
reswith the product of the last element andnum.
- Combine: Update the last element in
- Else, if the product is greater than
korresis empty, appendnumtores.
- If
-
Continue Until End: Repeat steps 2 and 3 until you have processed all elements in the input
numsarray. -
Return Result: The length of
resis 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
-
Initialization: Create an empty list
res. -
First Element (10):
resis empty, so add10tores.resbecomes[10]. -
Second Element (5): The product of
10(last element inres) and5is50, which is equal tok. Update the last element inreswith this product.resbecomes[50]. -
Third Element (2): The product of
50and2is100, which is greater thank. Add2tores.resbecomes[50, 2]. -
Fourth Element (3): The product of
2and3is6, which is less thank. Combine these into6.resbecomes[50, 6]. -
Fifth Element (4): The product of
6and4is24, which is less thank. Combine these into24.resbecomes[50, 24]. -
Sixth Element (2): The product of
24and2is48, which is less thank. Combine these into48.resbecomes[50, 48]. -
Seventh Element (20): The product of
48and20is960, which is greater thank. Add20tores.resbecomes[50, 48, 20]. -
Eighth Element (1): The product of
20and1is20, which is less thank. Combine these into20.resbecomes[50, 48, 20]. -
End of Input Array: We've processed all elements in
nums. -
Return Result: The length of
resis3. This is the minimum possible length of the array after performing the operations.
Code
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, wherenis 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 thereslist. 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.
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.
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.
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.
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.