DEV Community

Abubakar Sadiq Ismail
Abubakar Sadiq Ismail

Posted on

Find the element that appear once in array

Problem
Given an array with items.
each item in the array appear twice except once element.
E.g [1,4,3,4,1]
here the element 3 appear only once hence it should be returned.
Solution
Prerequisite knowledge hashMap or Dictionary.
How do you find the element.
Using Dictionary.

1 Create a Dictionary.
2 Assign the key of the dictionary as the array items, and the value as count of times it appears in the array.
3 Return the dictionary item with the value of 1.

Create items dictionary
Loop through the array i = 0,....n = length of the array-1.
If the array[i] is not a key in the items dictionary create a key with value of 1
if the array[i] is a key in the dictionary increment the value by 1.

Loop through the dictionary of items to get the key with 1 as value and return it, if all are more than one.

return -1.

Time Complexity O(n)
Because we are looping through the array n times.
Space Complexity O(n)
Because we are creating a map with at worst case n keys.

Top comments (0)