Grokking the Coding Interview: The Original Course
0% completed
Array Transformation (easy)
Problem Statement
Given an array arr, you transform it daily based on the following rules:
- If an element is smaller than both its left and right neighbors, increment it by
1. - If an element is larger than both its left and right neighbors, decrement it by
1. - The first and last elements of the array do not change.
Continue transforming the array until no more changes occur. Return the final state of the array.
Examples
Example 1
- Input: arr =
[5, 2, 8, 1, 6] - Expected Output:
[5, 5, 5, 5, 6] - Justification:
.....
.....
.....
Like the course? Get enrolled and start learning!
Shaurya Sood
· a month ago
import java.util.Arrays; class Solution { public int[] transformArray(int[] arr) { int[] prevVersion = new int[arr.length]; boolean done = false; while(!done){ prevVersion = arr.clone(); for(int i = 1; i < arr.length - 1; i++){ if(arr[i] < arr[i+1] && arr[i] < arr[i-1]) arr[i] = arr[i] + 1; else if(arr[i] > arr[i+1] && arr[i] > arr[i-1]) arr[i] = arr[i] - 1; else continue; } if(Arrays.equals(prevVersion, arr)) done = true; } return arr; } }
Reading Progress
0%