BackmediumArraysInfosys

Duplicate Element Identification Solution

Problem Statement

Given an array of integers containing elements from 1 to n, where n is the length of the array, identify all elements that appear exactly twice in the array and return them in a list.

Example 1
Input
[4, 3, 2, 7, 8, 2, 3, 1]
Output
[2, 3]

Explanation: Step-by-step: with input [4, 3, 2, 7, 8, 2, 3, 1], we count the occurrences of each element. We find that 2 and 3 appear exactly twice, so we return [2, 3].

Example 2
Input
[1, 2, 3, 4, 5, 6, 7, 8]
Output
[]

Explanation: Step-by-step: with input [1, 2, 3, 4, 5, 6, 7, 8], we count the occurrences of each element. We find that no elements appear exactly twice, so we return an empty list.

Constraints

  • 1 <= n <= 10^5
  • 1 <= arr[i] <= n
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Duplicate Element Identification — Problem Statement & Solution Guide

ArraysMediumCyclic Sort / Index Hashing
TimeO(n)
|
SpaceO(n)

Problem Description

Given an array of integers containing elements from 1 to n, where n is the length of the array, identify all elements that appear exactly twice in the array and return them in a list.

Examples

Example 1

Input

[4, 3, 2, 7, 8, 2, 3, 1]

Output

[2, 3]

Explanation: Step-by-step: with input [4, 3, 2, 7, 8, 2, 3, 1], we count the occurrences of each element. We find that 2 and 3 appear exactly twice, so we return [2, 3].

Example 2

Input

[1, 2, 3, 4, 5, 6, 7, 8]

Output

[]

Explanation: Step-by-step: with input [1, 2, 3, 4, 5, 6, 7, 8], we count the occurrences of each element. We find that no elements appear exactly twice, so we return an empty list.

Constraints

  • 1 <= n <= 10^5
  • 1 <= arr[i] <= n

Optimal Approach & Strategy

Iterate array. For each num, take absolute value as index. If value at that index is negative, num is a duplicate. Else, negate the value at that index. Time O(N), Space O(1).

Brute Force Approach

Use HashSet to find duplicates. Space O(N).

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums) { let count = {}; for (let num of nums) { if (count[num]) { count[num]++; } else { count[num] = 1; } } let result = []; for (let num in count) { if (count[num] === 2) { result.push(parseInt(num)); } } return result; }

Asked in Top Tech Interviews

Infosys

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.