Array Transformation - Problem

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.

Input & Output

Example 1 — Basic Transformation
$ Input: arr = [6,2,3,4]
Output: [6,4,4,4]
💡 Note: Day 1: 2<6 and 2<3, so 2→3. Array becomes [6,3,3,4]. Day 2: 3<6 and 3<3 (false), but middle 3<4, so 3→4. Continue until stable at [6,4,4,4].
Example 2 — Peak Reduction
$ Input: arr = [1,6,3,4,1]
Output: [1,4,4,4,1]
💡 Note: 6>1 and 6>3, so 6→5. Then 5>4 and 5>4, so 5→4. Process continues until all peaks are flattened to [1,4,4,4,1].
Example 3 — Already Stable
$ Input: arr = [2,1,1,1]
Output: [2,1,1,1]
💡 Note: Middle elements 1 are not smaller than both neighbors (1≮1), so no changes occur. Array is already stable.

Constraints

  • 1 ≤ arr.length ≤ 100
  • 1 ≤ arr[i] ≤ 100

Visualization

Tap to expand
Array Transformation In-Place Simulation Approach INPUT Initial Array: arr 6 i=0 2 i=1 3 i=2 4 i=3 Neighbor Comparison Rules: If element < both neighbors --> INCREMENT (+1) If element > both neighbors --> DECREMENT (-1) First & Last elements: NEVER change ALGORITHM STEPS 1 Day 0: [6,2,3,4] Check each middle element 2 Compare arr[1]=2 2 < 6 AND 2 < 3 --> +1 = 3 3 Compare arr[2]=3 3 < 6? NO --> No change Day 1: [6, 3, 3, 4] 4 Day 2: Check again arr[1]=3: 3 < 6 AND 3 < 3? NO Wait... 3 < 6 AND 3 = 3 Continue until stable... Repeat until no changes in consecutive days FINAL RESULT Stable Array (No More Changes) 6 fixed 4 2-->3-->4 4 3-->4 4 fixed Output: [6, 4, 4, 4] OK - Array is Stable! Transformation History: [6,2,3,4] Day 0 [6,3,3,4] Day 1 [6,4,4,4] Day 2 (Final) Key Insight: The simulation converges because each iteration reduces differences between neighbors. Elements "smooth out" toward their neighbors. The array stabilizes when no element is strictly smaller or larger than BOTH neighbors. Time: O(n * max_diff), Space: O(n) for temp array. TutorialsPoint - Array Transformation | In-Place Simulation Approach
Asked in
Google 15 Amazon 12 Apple 8 Facebook 6
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen