code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

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-31T20:49:21+05:18, updated 2021-02-03T00:21:14+05:18 · History · Edit