#1968
Array With Elements Not Equal to Average of Neighbors
MediumArrayGreedySortingGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n log n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach involves sorting the array and then rearranging it by placing smaller elements at odd indices and larger elements at even indices. This ensures that no element can be the average of its neighbors.
⚙️
Algorithm
3 steps- 1Step 1: Sort the array.
- 2Step 2: Create a new array of the same length.
- 3Step 3: Fill the new array with elements from the sorted array, placing smaller elements at odd indices and larger elements at even indices.
solution.py11 lines
1def rearrange(nums):
2 nums.sort()
3 n = len(nums)
4 result = [0] * n
5 mid = (n + 1) // 2
6 result[::2] = nums[:mid]
7 result[1::2] = nums[mid:]
8 return result
9
10# Example usage
11print(rearrange([1, 2, 3, 4, 5]))ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, and the space complexity is O(n) for the result array.
- 1Elements can only be the average of their neighbors if one neighbor is smaller and the other is larger.
- 2By sorting and distributing elements based on their size, we can avoid the average condition.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.