The Maximum Number of Distinct Elements After Operations coding problem gives you an array of integers and a value k. For each element, you can change it to any value in the range [element - k, element + k]. Maximize the number of distinct values in the resulting array. Each element is changed independently, but elements with the same target value would not be distinct.
Meta, Amazon, Google, and Bloomberg include this problem because it has a clean greedy solution that requires insight: process elements in sorted order and greedily assign the smallest valid target value that maintains distinctness. Candidates who recognize this greedy is globally optimal (not just locally) demonstrate strong mathematical reasoning.
Greedy with sorting: Sort the array. Process elements in sorted order. Maintain prev = the last assigned value (start at -infinity). For each element x:
[x - k, x + k].[x - k, x + k] that is greater than prev (to maintain distinctness).x - k > prev + 1: assign x - k (leave a gap, no need to squeeze).prev + 1 <= x + k: assign prev + 1 (squeeze in next consecutive value).Count elements successfully assigned distinct values.
Array: [1, 2, 3], k = 2.
Array: [1, 1, 1], k = 1.
For the Array Sorting Greedy interview pattern, the "assign smallest valid distinct value" greedy is a powerful pattern for distinct assignment problems. The key: sorted order + greedy minimum valid assignment = maximum distinct count. Practice on similar problems like "assign unique integers to minimize max" to internalize the technique.