Skip to content

Commit 06ce0bb

Browse files
authored
create find non repeating elements
1 parent 93a1781 commit 06ce0bb

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

find_non_repeating_elements.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
arr = [1,2,3,7,3,2]
2+
3+
"""
4+
# Approach 1: Brute-force approach
5+
# Complexity: n-squared
6+
"""
7+
def ispresent(arr, a):
8+
if a in arr:
9+
return 1
10+
else:
11+
return 0
12+
13+
passed_entries = []
14+
entries_count = []
15+
for i in range(0, len(arr)):
16+
if ispresent(passed_entries, arr[i]) == 0:
17+
passed_entries.append(arr[i])
18+
entries_count.append(1)
19+
else:
20+
entries_count[passed_entries.index(arr[i])] += 1
21+
22+
23+
for i in range(len(entries_count)):
24+
if entries_count[i] == 1:
25+
print("Methid 1: Non-repeating entry ", passed_entries[i])
26+
27+
28+
"""
29+
# Approach 2: Hash Map
30+
# Complexity: O(n)
31+
# For this approach to work the pre-requisite is to have all positive number in the array. The downside of using this approach is to have extra memory requirement.
32+
"""
33+
entries_count = [0]*(max(arr)+1)
34+
for i in range(len(arr)):
35+
entries_count[arr[i]] += 1
36+
37+
for i in range(len(entries_count)):
38+
if entries_count[i] == 1:
39+
print("Method 2: Non-repeating entry ", i)
40+
41+
42+
"""
43+
# Approach 3: Using XOR operation
44+
# Complexity: O(n)
45+
# This is the best possible method to find a non-repeated entry in an array.
46+
# Downside of this method is that this method can find atmost 2 non-repeated enteries in a list.
47+
"""
48+
import math
49+
def getFirstSetBitPos(n):
50+
return int(math.log2(n&-n)+1)
51+
52+
xor = 0
53+
for i in range(len(arr)):
54+
xor ^= arr[i]
55+
56+
index = getFirstSetBitPos(xor)
57+
58+
grp1 =[]
59+
grp2 = []
60+
61+
for i in range(len(arr)):
62+
x = (arr[i])>>(index-1)
63+
if x%2 == 1:
64+
grp1.append(arr[i])
65+
else:
66+
grp2.append(arr[i])
67+
68+
result = []
69+
r = 0
70+
for i in range(len(grp1)):
71+
r ^= grp1[i]
72+
print("Method 3: Non-repeating entry is ", r)
73+
74+
r = 0
75+
for i in range(len(grp2)):
76+
r ^= grp2[i]
77+
print("Method 3: Non-repeating entry is ", r)

0 commit comments

Comments
 (0)