BackeasyHashingAmazonCognizant

Single Occurrence Identifier Solution

Problem Statement

Given a non-empty array of integers, every element appears twice except for one. Find the first element that appears once in the order they appear in the array. If no such element exists, return 'there is no unique number'.

Example 1
Input
[2, 3, 5, 4, 5, 3, 4]
Output
2

Explanation: Step-by-step: with input [2, 3, 5, 4, 5, 3, 4], we create a frequency map. The first element that appears once is 2, so the output is 2.

Example 2
Input
[10, 20, 10, 30, 30, 40, 40]
Output
20

Explanation: Step-by-step: with input [10, 20, 10, 30, 30, 40, 40], we create a frequency map. The first element that appears once is 20, so the output is 20.

Constraints

  • 1 <= n <= 10^5
  • n is always odd.
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

Single Occurrence Identifier — Problem Statement & Solution Guide

HashingEasyBit Manipulation / Hashing
TimeO(n)
|
SpaceO(n)

Problem Description

Given a non-empty array of integers, every element appears twice except for one. Find the first element that appears once in the order they appear in the array. If no such element exists, return 'there is no unique number'.

Examples

Example 1

Input

[2, 3, 5, 4, 5, 3, 4]

Output

2

Explanation: Step-by-step: with input [2, 3, 5, 4, 5, 3, 4], we create a frequency map. The first element that appears once is 2, so the output is 2.

Example 2

Input

[10, 20, 10, 30, 30, 40, 40]

Output

20

Explanation: Step-by-step: with input [10, 20, 10, 30, 30, 40, 40], we create a frequency map. The first element that appears once is 20, so the output is 20.

Constraints

  • 1 <= n <= 10^5
  • n is always odd.

Optimal Approach & Strategy

Use a hash map to count the occurrences of each batch ID in O(n) time complexity

Brute Force Approach

Compare each batch ID with every other batch ID to find the one that appears exactly once

Verified Code Solutions

JavaScript Solution
Time: O(n)
function solution(nums) {
       let map = new Map();
       for (let num of nums) {
           if (map.has(num)) {
               map.set(num, map.get(num) + 1);
           } else {
               map.set(num, 1);
           }
       }
       for (let num of nums) {
           if (map.get(num) === 1) {
               return num;
           }
       }
       return 'there is no unique number';
   }

Asked in Top Tech Interviews

AmazonCognizant

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.