Array Transformation Problem
Description
LeetCode Problem 1243.
Given an initial array arr, every day you produce a new array using the array of the previous day.
On the i-th day, you do the following operations on the array of day i-1 to produce the array of day i:
- If an element is smaller than both its left neighbor and its right neighbor, then this element is incremented.
- If an element is bigger than both its left neighbor and its right neighbor, then this element is decremented.
- The first and last elements never change.
After some days, the array does not change. Return that final array.
Example 1:
Input: arr = [6,2,3,4]
Output: [6,3,3,4]
Explanation:
On the first day, the array is changed from [6,2,3,4] to [6,3,3,4].
No more operations can be done to this array.
Example 2:
Input: arr = [1,6,3,4,3,5]
Output: [1,4,4,4,4,5]
Explanation:
On the first day, the array is changed from [1,6,3,4,3,5] to [1,5,4,3,4,5].
On the second day, the array is changed from [1,5,4,3,4,5] to [1,4,4,4,4,5].
No more operations can be done to this array.
Constraints:
3 <= arr.length <= 1001 <= arr[i] <= 100
Solution
Approach: Simulate Day by Day
The rules are simple, and the array settles quickly, so we can just simulate. Each day, every inner element arr[i] (not the first or last) changes by the rule:
- smaller than both neighbours: increment it;
- bigger than both neighbours: decrement it.
The tricky part is that all changes of one day happen at once, based on the array of the day before. If we updated arr in place while scanning, arr[i + 1] would compare against the already changed arr[i]. So each day we copy the array first and read the neighbours from the copy. When a whole day passes with no change, the array is final.
It always stops: each change lowers a peak or raises a valley without passing its neighbours, so the values stay between the smallest and largest original value and the array only gets flatter, until no peak or valley is left.
Complexity: O(n · V) time, where n is the length and V the largest value (at most about V days, each O(n)), and O(n) extra space for the copy.
class Solution:
def transformArray(self, arr: List[int]) -> List[int]:
changed = True
while changed:
changed = False
prev = arr[:] # every change of a day looks at the array of the day before
for i in range(1, len(arr) - 1):
if prev[i] < prev[i - 1] and prev[i] < prev[i + 1]:
arr[i] += 1
changed = True
elif prev[i] > prev[i - 1] and prev[i] > prev[i + 1]:
arr[i] -= 1
changed = True
return arr