code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

017 Array Previous Less

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

/* 
Given array of integers, for each position i, search among the previous positions for the last (from the left) position that contains a smaller values. Store this value at position i in the answer. If no such value can be found, store -1 instead.

Example

For items = [3, 5, 2, 4, 5], the output should be arrayPreviousLess(items) = [-1, 3, -1, 2, 4]. 
*/

function arrayPreviousLess(array) {
  let results = []
  for (let i = 0; i < array.length; i++) {
    let newValue = -1
    for (let j = 0; j < i; j++) {
      if (array[j] < array[i]) {
        newValue = array[j]
      }
    }
    results.push(newValue)
  }
  return results
}

test('array Previous Less', () => {
  expect(arrayPreviousLess([3, 5, 2, 4, 5])).toEqual([-1, 3, -1, 2, 4])
  expect(arrayPreviousLess([2, 2, 1, 3, 4, 5, 5, 3])).toEqual([-1, -1, -1, 1, 3, 4, 4, 1])
})

Created 2019-12-09T02:17:09+05:30 · Edit