LeetCode 1243. Array Transformation

Description

https://leetcode.com/problems/array-transformation/

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:

  1. If an element is smaller than both its left neighbor and its right neighbor, then this element is incremented.
  2. If an element is bigger than both its left neighbor and its right neighbor, then this element is decremented.
  3. 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 <= 100
  • 1 <= arr[i] <= 100

Explanation

The list length indicates how many times we need to transform the array.

Python Solution

class Solution:
    def transformArray(self, arr: List[int]) -> List[int]:
        
        arr_num = list(arr)
        
        for k in range(len(arr_num)):

            results = []

            for i, num in enumerate(arr_num):
                if i != 0 and i != len(arr_num) - 1:
                    if num > arr_num[i - 1] and num > arr_num[i + 1]:
                        results.append(num - 1)
                    elif num < arr_num[i - 1] and num < arr_num[i + 1]:
                        results.append(num + 1)
                    else:
                        results.append(num)
                else:
                    results.append(num)
            
            arr_num = results
        
        return arr_num
  • Time Complexity: O(N^2).
  • Space Complexity: O(N).

Leave a Reply

Your email address will not be published. Required fields are marked *