DEV Community

Abubakar Sadiq Ismail
Abubakar Sadiq Ismail

Posted on

1

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay