diff --git a/problems/array-transformation/README.md b/problems/array-transformation/README.md new file mode 100644 index 0000000..11871de --- /dev/null +++ b/problems/array-transformation/README.md @@ -0,0 +1,7 @@ +# Array Transformation + +LeetCode #: [1243](https://leetcode.com/problems/array-transformation/) + +Difficulty: Easy + +Topic: Array. diff --git a/problems/array-transformation/solution.js b/problems/array-transformation/solution.js new file mode 100644 index 0000000..66c45aa --- /dev/null +++ b/problems/array-transformation/solution.js @@ -0,0 +1,32 @@ +const transformArray = (arr) => { + if (arr.length <= 2) { + return arr + } + + const result = arr.slice() + let changed + let init + + do { + changed = false + init = result.slice() + + for (let i = 1; i < init.length - 1; i++) { + const element = init[i] + const left = init[i - 1] + const right = init[i + 1] + + if (element > left && element > right) { + result[i] = element - 1 + changed = true + } else if (element < left && element < right) { + result[i] = element + 1 + changed = true + } + } + } while (changed) + + return result +} + +module.exports = transformArray diff --git a/problems/array-transformation/solution.test.js b/problems/array-transformation/solution.test.js new file mode 100644 index 0000000..42cfa8a --- /dev/null +++ b/problems/array-transformation/solution.test.js @@ -0,0 +1,49 @@ +const transformArray = require('./solution') + +test('Example 1', () => { + const arr = [6, 2, 3, 4] + + const result = transformArray(arr) + + expect(result).toStrictEqual([6, 3, 3, 4]) +}) + +test('Example 2', () => { + const arr = [1, 6, 3, 4, 3, 5] + + const result = transformArray(arr) + + expect(result).toStrictEqual([1, 4, 4, 4, 4, 5]) +}) + +test('Array length 1, should return same thing', () => { + const arr = [5] + + const result = transformArray(arr) + + expect(result).toStrictEqual([5]) +}) + +test('Array length 2, should return same thing', () => { + const arr = [5, 3] + + const result = transformArray(arr) + + expect(result).toStrictEqual([5, 3]) +}) + +test('not bigger or smaller on both side, should return same thing', () => { + const arr = [1, 2, 2, 3, 3, 4] + + const result = transformArray(arr) + + expect(result).toStrictEqual([1, 2, 2, 3, 3, 4]) +}) + +test('not bigger or smaller on both side, values higher than first and last element, should return same thing', () => { + const arr = [1, 55, 55, 33, 33, 10] + + const result = transformArray(arr) + + expect(result).toStrictEqual([1, 55, 55, 33, 33, 10]) +})