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

442 Find All Duplicates In An Array

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

const findAllDuplicatesInAnArray = nums => {
  let result = []
  for (let i = 0; i < nums.length; i++) {
    const index = Math.abs(nums[i]) - 1
    if (nums[index] < 0) {
      result.push(index + 1)
    }
    nums[index] = -nums[index]
  }
  return result
}

test('findAllDuplicatesInAnArray', () => {
  expect(findAllDuplicatesInAnArray([4, 3, 2, 7, 8, 2, 3, 1])).toEqual([2, 3])
})

Created 2021-01-31T21:01:21+05:30, updated 2021-02-03T00:33:14+05:30 · History · Edit