You are given an array of integers nums. Some values in nums are missing and are denoted by -1.
You can choose a pair of positive integers (x, y) exactly once and replace each missing element with either x or y.
You need to minimize the maximum absolute difference between adjacent elements of nums after replacements.
Return the minimum possible difference.
Example 1:
Input: nums = [1,2,-1,10,8]
Output: 4
Explanation:
By choosing the pair as (6, 7), nums can be changed to [1, 2, 6, 10, 8].
The absolute differences between adjacent elements are:
|1 - 2| == 1|2 - 6| == 4|6 - 10| == 4|10 - 8| == 2Example 2:
Input: nums = [-1,-1,-1]
Output: 0
Explanation:
By choosing the pair as (4, 4), nums can be changed to [4, 4, 4].
Example 3:
Input: nums = [-1,10,-1,8]
Output: 1
Explanation:
By choosing the pair as (11, 9), nums can be changed to [11, 10, 9, 8].
Constraints:
2 <= nums.length <= 105nums[i] is either -1 or in the range [1, 109].Problem Overview: You are given an array where some elements may be missing and must be replaced. The goal is to choose replacement values so that the maximum absolute difference between adjacent elements is minimized. The challenge is deciding which values to insert while keeping the largest neighbor gap as small as possible.
Approach 1: Greedy with Adjacent Difference Calculation (O(n) time, O(1) space)
Scan the array and focus on positions where a missing value sits between known neighbors. Track the minimum and maximum values around these gaps and estimate the best replacement that minimizes the largest adjacent difference. This method computes candidate values directly while iterating once through the array. It works well when the replacement pattern is straightforward and most constraints come from immediate neighbors.
Approach 2: Greedy Replacement with Median Strategy (O(n) time, O(1) space)
Instead of testing many replacements, compute the range of values surrounding missing segments and place a value near the median of that range. The intuition is that choosing a midpoint balances the difference on both sides of the gap. While iterating through the array, maintain boundary values for each missing block and greedily assign replacements that minimize the worst adjacent difference. This technique reduces variance across neighbors and often produces the optimal answer in a single pass.
Approach 3: Binary Search on Possible Values (O(n log M) time, O(1) space)
Binary search the answer for the smallest possible maximum difference d. For each candidate d, iterate through the array and check whether it is possible to fill missing values so every adjacent pair differs by at most d. The check function greedily determines valid ranges for replacements and verifies that constraints are satisfiable. Binary search works because the feasibility of a given d is monotonic.
Approach 4: Binary Search on Minimum Difference (O(n log M) time, O(1) space)
This variation also uses binary search but frames the feasibility check more explicitly around valid intervals for replacements. As you iterate through the array, compute allowable ranges that keep differences within d. Intersect these ranges for consecutive constraints and confirm whether at least one valid value exists for each missing position. This approach is reliable for complex configurations of gaps and constraints.
Recommended for interviews: The Binary Search feasibility approach combined with greedy validation is the most expected solution. It clearly demonstrates how to convert an optimization problem into a monotonic decision problem. Understanding the simpler greedy observations over arrays and constraint balancing also helps justify why the greedy check works.
The key observation here is that by choosing an optimal pair (x, y) to replace -1s, the problem boils down to minimizing the maximum difference between adjacent elements. A possible solution approach is to perform binary search on the potential values of replacement integers. For each test value in the binary search, validate whether there's a valid pair (x, y) such that the maximum absolute difference of adjacent elements can be minimized.
This Python solution employs binary search on the potential values for the maximum difference. The helper function isValid() checks if a candidate difference can be maintained across the array. By iterating through the array, checking the difference with a running prev reference, and adapting the search based on the feasibility results of isValid(), the algorithm narrows down to the minimal difference.
Python
Time Complexity: O(n log M), where n is the length of the nums array and M is the range of possible numbers (10^9 in this case).
Space Complexity: O(1), only constant extra space needed.
This greedy approach suggests that as midpoints, both chosen replacements might offer a simpler minimization for adjacent differences. By calculating the potential impact for values between the minimum and maximum non-negative integers in the array, setting replacements near the midpoints can minimize adjacent differences in a more predictable way.
This C++ implementation first finds the minimum and maximum existing numbers in the array and calculates their midpoint as a trial replacement for -1s. Then it updates the array and calculates the maximum adjacent difference post-replacement, returning it as the solution. The greedy strategy exploits the condition easing given by the use of median replacement.
C++
Time Complexity: O(n), where n is the size of the nums array due to linear scanning and processing.
Space Complexity: O(1), since operations are in place and require no additional data structures.
This approach involves scanning through the array to track and calculate the necessary replacements. You need to compute the adjacent differences and use them to identify optimal replacement values for missing elements (-1).
Use a greedy strategy to select values that minimize the maximum difference between non-missing elements after replacements.
The provided Python solution iterates through the input to discover segments of consecutive -1 entries. For each such segment, it checks neighboring elements (left and right of the -1s) to determine possible replacements.
Then, we calculate the maximum difference possible for various (x, y) pairs to choose values minimizing the overall impact. The function 'max_diff' is used to compute the resulting max difference after replacements. Finally, the minimum of these differences for given replacements is returned.
Time Complexity: O(n)
Space Complexity: O(1) (ignoring space for output storage)
This approach utilizes binary search to identify the smallest possible maximum difference that can be achieved when choosing replacement values for -1's in the array. By searching for the smallest maximum difference across all possible (x, y) pairs, this method finds the optimal solution efficiently. We simulate the maximum difference scenario using a helper function to validate each potential maximum difference candidate.
This Java solution employs binary search to find the minimum achievable maximum difference between adjacent elements after replacing the -1s. In the helper function isFeasible, we simulate replacements and check if the desired maximum difference can be maintained throughout the array.
Java
JavaScript
Time Complexity: O(n log M), where M is the maximum value of elements
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Binary Search on Possible Values | Time Complexity: O(n log M), where n is the length of the |
| Greedy Replacement with Median Strategy | Time Complexity: O(n), where n is the size of the |
| Greedy Approach with Adjacent Difference Calculation | Time Complexity: O(n) |
| Binary Search on Minimum Difference | Time Complexity: O(n log M), where M is the maximum value of elements |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy with Adjacent Difference Calculation | O(n) | O(1) | When constraints mostly depend on immediate neighbors and gaps are simple |
| Greedy Median Replacement | O(n) | O(1) | When missing segments can be balanced using midpoint values |
| Binary Search on Possible Values | O(n log M) | O(1) | General case; reliable method for interview settings |
| Binary Search with Range Validation | O(n log M) | O(1) | When multiple gaps create overlapping constraints on valid values |
Minimize the Maximum Adjacent Element Difference | Detailed Explanation | Leetcode 3357 | MIK • codestorywithMIK • 4,830 views views
Watch 5 more video solutions →Practice Minimize the Maximum Adjacent Element Difference with our built-in code editor and test cases.
Practice on FleetCode