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 Length of Array Using Operations INPUT Initial Array: nums 5 i=0 2 i=1 3 i=2 Input Details nums = [5, 2, 3] Length: 3 Allowed Operation 1. Pick i, j where a[i],a[j] > 0 2. Add (a[i] % a[j]) to end 3. Remove a[i] and a[j] ALGORITHM STEPS 1 Find Minimum min(nums) = 2 2 Apply Operation 5 % 2 = 1, remove 5,2 3 New Array nums = [3, 1] 4 Continue 3 % 1 = 0, remove 3,1 Greedy Strategy [5,2,3] --> [3,1] --> [0] 5%2=1 added 3%1=0 added Zero elements can be removed with any pair FINAL RESULT Minimized Array 1 Minimum Length: 1 Output 1 Verification Start: 3 elements After op 1: 2 elements After op 2: 1 element [OK] Key Insight: Using the modulo operation repeatedly with the minimum element creates smaller values. Eventually, we can reduce any element to 0 using (x % min). Zero pairs can eliminate each other, leaving at most 1 element. Greedy: always use the smallest non-zero value for modulo operations. TutorialsPoint - Minimize Length of Array Using Operations | Greedy Strategy with Priority
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