Minimum Operations to Make Array Elements Zero - Problem

You are given a 2D array queries, where queries[i] is of the form [l, r]. Each queries[i] defines an array of integers nums consisting of elements ranging from l to r, both inclusive.

In one operation, you can:

  • Select two integers a and b from the array.
  • Replace them with floor(a / 4) and floor(b / 4).

Your task is to determine the minimum number of operations required to reduce all elements of the array to zero for each query. Return the sum of the results for all queries.

Input & Output

Example 1 — Basic Range
$ Input: queries = [[1,3]]
Output: 3
💡 Note: Range [1,3]: 1 needs 1 op (1→0), 2 needs 1 op (2→0), 3 needs 1 op (3→0). Total: 1+1+1 = 3.
Example 2 — Larger Numbers
$ Input: queries = [[5,7]]
Output: 6
💡 Note: Range [5,7]: 5→1→0 (2 ops), 6→1→0 (2 ops), 7→1→0 (2 ops). Total: 2+2+2 = 6
Example 3 — Multiple Queries
$ Input: queries = [[1,2],[3,4]]
Output: 5
💡 Note: Query [1,2]: 1→0 (1 op), 2→0 (1 op). Sum=2. Query [3,4]: 3→0 (1 op), 4→1→0 (2 ops). Sum=3. Total: 2+3 = 5.

Constraints

  • 1 ≤ queries.length ≤ 105
  • 1 ≤ l ≤ r ≤ 106

Visualization

Tap to expand
Minimum Operations to Make Array Elements Zero INPUT Query: [l, r] = [1, 3] Generated Array: 1 2 3 [0] [1] [2] Operations to reach 0: 1 --> 0 1 op 2 --> 0 1 op 3 --> 0 1 op Input: queries = [[1, 3]] ALGORITHM STEPS 1 Precompute ops(n) Count: n --> n/4 until 0 2 For each query [l,r] Build array nums = [l...r] 3 Pair elements Process 2 elements per op 4 Sum all operations Total = sum of ops needed Calculation: 1: 1/4=0 (1 step) 2: 2/4=0 (1 step) 3: 3/4=0 (1 step) Each pair needs 2 ops Total: 1+2+3 pairs = 6 FINAL RESULT All elements reduced to zero 0 0 0 OK OK OK Operations Breakdown: Element 1: 1 op Element 2: 2 ops Element 3: 3 ops Sum: 1+2+3 = 6 Output: 6 Key Insight: Each operation can process TWO elements simultaneously by dividing both by 4. For number n, it takes ceil(log4(n)) operations to reduce to 0. The total ops equals sum of individual element operations when paired optimally. For [1,3]: 1+2+3 = 6. TutorialsPoint - Minimum Operations to Make Array Elements Zero | Precomputed Operations
Asked in
Google 15 Microsoft 12 Amazon 10
23.4K Views
Medium Frequency
~25 min Avg. Time
856 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