We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Array Transformation

Number: 1175

Difficulty: Easy

Paid? Yes

Companies: Virtu Financial


Problem Description

Given an initial array arr, we repeatedly transform the array day by day. For each day, for every element except the first and the last, if it is smaller than both its left and right neighbors then it is incremented by one; if it is larger than both its left and right neighbors then it is decremented by one. The process continues until no more changes occur and the final array is stable.


Key Insights

  • Simulate the transformation process day by day.
  • Only the inner elements are updated, while the first and last elements remain constant.
  • The algorithm stops when a complete iteration over the array results in no changes.
  • Since the array length is small, a brute-force simulation is efficient enough.

Space and Time Complexity

Time Complexity: O(t * n), where n is the length of the array and t is the number of days until stabilization. Space Complexity: O(n), for storing the transformed array for each day.


Solution

The problem is solved by simulating the transformation process. On each day, a new array is created based on the previous day's array. For every inner element in the array, we check if the element is smaller than both its neighbors (and increment it) or larger than both (and decrement it). The simulation stops when an iteration produces no changes. The algorithm uses an iterative approach with an auxiliary array to compute the next day's state.


Code Solutions

def transformArray(arr):
    changed = True  # Flag to check if any change happened during the pass
    while changed:
        changed = False
        # Create a copy of the array to store transformations for the next day
        new_arr = arr[:]  
        # Process each element except the first and the last
        for i in range(1, len(arr) - 1):
            if arr[i] < arr[i - 1] and arr[i] < arr[i + 1]:
                new_arr[i] = arr[i] + 1  # Increment if smaller than both neighbors
                changed = True
            elif arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:
                new_arr[i] = arr[i] - 1  # Decrement if larger than both neighbors
                changed = True
        # Update arr with new_arr for the next iteration
        arr = new_arr
    return arr

# Example usage:
print(transformArray([6,2,3,4]))  # Output: [6,3,3,4]
← Back to All Questions