Skip to content

Commit

Permalink
added working solution for #1243.
Browse files Browse the repository at this point in the history
  • Loading branch information
ecgan committed Nov 2, 2019
1 parent abd170b commit 93881ea
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 0 deletions.
7 changes: 7 additions & 0 deletions problems/array-transformation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Array Transformation

LeetCode #: [1243](https://leetcode.com/problems/array-transformation/)

Difficulty: Easy

Topic: Array.
32 changes: 32 additions & 0 deletions problems/array-transformation/solution.js
Original file line number Diff line number Diff line change
@@ -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
49 changes: 49 additions & 0 deletions problems/array-transformation/solution.test.js
Original file line number Diff line number Diff line change
@@ -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])
})

0 comments on commit 93881ea

Please sign in to comment.