Count how many array elements must be changed so that every value becomes exactly k.
Problem
You are given an integer array nums and an integer k.
In one operation, you may choose any index and change nums[i] to any value you want.
Return the minimum number of operations required so that every element in the array is equal to k.
Idea
This is a direct counting problem: only elements that are already equal to k can stay unchanged. Every other element must be modified exactly once.
Input Format
- An integer array
nums - An integer
k
Output Format
- Return the minimum number of single-index value changes needed so that all elements equal
k.
Constraints
- 1 <= nums.length
- nums[i] and k are integers
- Each operation changes one array element
- The answer is always between
0andnums.length
Example 1
Input
nums = [3, 1, 3, 2], k = 3
Output
2
Explanation
The two elements not equal to 3 must be changed. After 2 operations, the array can become [3, 3, 3, 3].
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.