Minimize Length of Array Using Operations - Problem

You are given a 0-indexed integer array nums containing positive integers.

Your task is to minimize the length of nums by performing the following operations any number of times (including zero):

  • Select two distinct indices i and j from nums, such that nums[i] > 0 and nums[j] > 0.
  • Insert the result of nums[i] % nums[j] at the end of nums.
  • Delete the elements at indices i and j from nums.

Return an integer denoting the minimum length of nums after performing the operation any number of times.

Input & Output

Example 1 — Basic Reduction
$ Input: nums = [5, 2, 3]
Output: 1
💡 Note: We can perform operations: 5 % 2 = 1, giving [3, 1]. Then 3 % 1 = 0, removing both elements. Final length is 1 with remaining element from previous operations.
Example 2 — Multiple Operations
$ Input: nums = [6, 4, 2]
Output: 1
💡 Note: 6 % 2 = 0, so we remove both 6 and 2, left with [4]. Since we can't reduce further, minimum length is 1.
Example 3 — Single Element
$ Input: nums = [7]
Output: 1
💡 Note: Array has only one element, so no operations can be performed. Minimum length remains 1.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 106
  • All elements in nums are positive integers

Visualization

Tap to expand
Minimize Array Length Using OperationsInitial Array5235 % 2 = 1After Operation313 % 1 = 0Final Result1Length = 1Operations: Select two elements → Compute remainder → Replace/RemoveGoal: Minimize final array length
Understanding the Visualization
1
Input
Array [5, 2, 3] with 3 elements
2
Operations
Apply a % b operations to combine elements
3
Output
Minimum achievable length: 1
Key Takeaway
🎯 Key Insight: Modulo operations systematically reduce array elements toward their GCD, enabling significant size reduction
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen