NeetCode #88LC-1243EasyArrays & Hashing
← Back to All Problems#88 · #1243 · Array Transformation(数组变换)
📌 Problem Statement & Constraints
Given an integer array
arr, repeatedly apply this transformation simultaneously to every interior element: increase it by 1 if it is smaller than both neighbours, decrease it by 1 if it is larger than both, otherwise leave it unchanged. Return the array once no further changes occur. Constraints: 3 <= arr.length <= 100, 1 <= arr[i] <= 100.💡 Core Algorithmic Approaches
- This is a direct simulation: build the next state from the current one, and stop when the state stops changing.
- The update must be simultaneous, so write into a copy rather than mutating
arrin place. - Only interior indices
1..n-2are affected, since the endpoints have no two neighbours. - Termination is guaranteed because each element is bounded and the changes are monotone in a potential sense -- in practice the array settles within a few rounds.
💻 Benchmark Python3 Implementation
class Solution:
def transformArray(self, arr: List[int]) -> List[int]:
while True:
nxt = arr[:] # simultaneous update needs a copy
for i in range(1, len(arr) - 1):
if arr[i] < arr[i - 1] and arr[i] < arr[i + 1]:
nxt[i] += 1
elif arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:
nxt[i] -= 1
if nxt == arr: # fixed point reached
return arr
arr = nxt⚡ Complexity Deep Dive
⏱️ Time Complexity
O(rounds * n). The number of rounds is bounded by the value range (at most 100), so this is O(100 * n) = O(n) in practice.
💾 Space Complexity
O(n) for the working copy each round.
⚠️ Interview Pitfalls & Follow-ups
- Updating
arrin place: neighbours would see partially updated values, which is not what the simultaneous rule means. - Applying the rule to the endpoints: indices 0 and n-1 have no two neighbours and must never change.
- Returning
nxtinstead ofarr: both are equal at the fixed point, but returning the original reference is clearer. - Comparing
nxt != arrwithis:iscompares identity, not contents.