Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an array nums consisting of positive integers.
You are also given an integer array queries of size m. For the ith query, you want to make all of the elements of nums equal to queries[i]. You can perform the following operation on the array any number of times:
1.Return an array answer of size m where answer[i] is the minimum number of operations to make all elements of nums equal to queries[i].
Note that after each query the array is reset to its original state.
Example 1:
Input: nums = [3,1,6,8], queries = [1,5] Output: [14,10] Explanation: For the first query we can do the following operations: - Decrease nums[0] 2 times, so that nums = [1,1,6,8]. - Decrease nums[2] 5 times, so that nums = [1,1,1,8]. - Decrease nums[3] 7 times, so that nums = [1,1,1,1]. So the total number of operations for the first query is 2 + 5 + 7 = 14. For the second query we can do the following operations: - Increase nums[0] 2 times, so that nums = [5,1,6,8]. - Increase nums[1] 4 times, so that nums = [5,5,6,8]. - Decrease nums[2] 1 time, so that nums = [5,5,5,8]. - Decrease nums[3] 3 times, so that nums = [5,5,5,5]. So the total number of operations for the second query is 2 + 4 + 1 + 3 = 10.
Example 2:
Input: nums = [2,9,6,3], queries = [10] Output: [20] Explanation: We can increase each value in the array to 10. The total number of operations will be 8 + 1 + 4 + 7 = 20.
Constraints:
n == nums.lengthm == queries.length1 <= n, m <= 1051 <= nums[i], queries[i] <= 109Problem summary: You are given an array nums consisting of positive integers. You are also given an integer array queries of size m. For the ith query, you want to make all of the elements of nums equal to queries[i]. You can perform the following operation on the array any number of times: Increase or decrease an element of the array by 1. Return an array answer of size m where answer[i] is the minimum number of operations to make all elements of nums equal to queries[i]. Note that after each query the array is reset to its original state.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search
[3,1,6,8] [1,5]
[2,9,6,3] [10]
minimum-moves-to-equal-array-elements-ii)minimum-cost-to-make-array-equal)sum-of-distances)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2602: Minimum Operations to Make All Array Elements Equal
class Solution {
public List<Long> minOperations(int[] nums, int[] queries) {
Arrays.sort(nums);
int n = nums.length;
long[] s = new long[n + 1];
for (int i = 0; i < n; ++i) {
s[i + 1] = s[i] + nums[i];
}
List<Long> ans = new ArrayList<>();
for (int x : queries) {
int i = search(nums, x + 1);
long t = s[n] - s[i] - 1L * (n - i) * x;
i = search(nums, x);
t += 1L * x * i - s[i];
ans.add(t);
}
return ans;
}
private int search(int[] nums, int x) {
int l = 0, r = nums.length;
while (l < r) {
int mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
}
// Accepted solution for LeetCode #2602: Minimum Operations to Make All Array Elements Equal
func minOperations(nums []int, queries []int) (ans []int64) {
sort.Ints(nums)
n := len(nums)
s := make([]int, n+1)
for i, x := range nums {
s[i+1] = s[i] + x
}
for _, x := range queries {
i := sort.SearchInts(nums, x+1)
t := s[n] - s[i] - (n-i)*x
i = sort.SearchInts(nums, x)
t += x*i - s[i]
ans = append(ans, int64(t))
}
return
}
# Accepted solution for LeetCode #2602: Minimum Operations to Make All Array Elements Equal
class Solution:
def minOperations(self, nums: List[int], queries: List[int]) -> List[int]:
nums.sort()
s = list(accumulate(nums, initial=0))
ans = []
for x in queries:
i = bisect_left(nums, x + 1)
t = s[-1] - s[i] - (len(nums) - i) * x
i = bisect_left(nums, x)
t += x * i - s[i]
ans.append(t)
return ans
// Accepted solution for LeetCode #2602: Minimum Operations to Make All Array Elements Equal
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2602: Minimum Operations to Make All Array Elements Equal
// class Solution {
// public List<Long> minOperations(int[] nums, int[] queries) {
// Arrays.sort(nums);
// int n = nums.length;
// long[] s = new long[n + 1];
// for (int i = 0; i < n; ++i) {
// s[i + 1] = s[i] + nums[i];
// }
// List<Long> ans = new ArrayList<>();
// for (int x : queries) {
// int i = search(nums, x + 1);
// long t = s[n] - s[i] - 1L * (n - i) * x;
// i = search(nums, x);
// t += 1L * x * i - s[i];
// ans.add(t);
// }
// return ans;
// }
//
// private int search(int[] nums, int x) {
// int l = 0, r = nums.length;
// while (l < r) {
// int mid = (l + r) >> 1;
// if (nums[mid] >= x) {
// r = mid;
// } else {
// l = mid + 1;
// }
// }
// return l;
// }
// }
// Accepted solution for LeetCode #2602: Minimum Operations to Make All Array Elements Equal
function minOperations(nums: number[], queries: number[]): number[] {
nums.sort((a, b) => a - b);
const n = nums.length;
const s: number[] = new Array(n + 1).fill(0);
for (let i = 0; i < n; ++i) {
s[i + 1] = s[i] + nums[i];
}
const search = (x: number): number => {
let l = 0;
let r = n;
while (l < r) {
const mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
const ans: number[] = [];
for (const x of queries) {
const i = search(x + 1);
let t = s[n] - s[i] - (n - i) * x;
const j = search(x);
t += x * j - s[j];
ans.push(t);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.