Array With Elements Not Equal to Average of Neighbors — LeetCode 1968 Python Solution

MediumGreedyArraySorting
Problem
#1968
Pattern
Greedy
Reading time
2 min

The problem

You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.

Example

Input
nums = [1,2,3,4,5]
Output
[1,2,4,5,3]
Explanation
When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.

Python solution

Python
class Solution:
    def rearrangeArray(self, nums: List[int]) -> List[int]:
        nums.sort()
        n = len(nums)
        m = (n + 1) // 2
        ans = []
        for i in range(m):
            ans.append(nums[i])
            if i + m < n:
                ans.append(nums[i + m])
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1968. Array With Elements Not Equal to Average of Neighbors is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1968. Array With Elements Not Equal to Average of Neighbors?
LeetCode 1968. Array With Elements Not Equal to Average of Neighbors is rated Medium on LeetCode.
What is the time complexity of LeetCode 1968. Array With Elements Not Equal to Average of Neighbors?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1968. Array With Elements Not Equal to Average of Neighbors?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1968. Array With Elements Not Equal to Average of Neighbors cover?
LeetCode 1968. Array With Elements Not Equal to Average of Neighbors is tagged Greedy, Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview