Skip to content

Commit 0da2929

Browse files
committed
Print all distinct elements in array
1 parent c705a87 commit 0da2929

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Diff for: arrays/PrintDistinct.rb

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#Given an array which may contain duplicates,print all distinct elements.
2+
#e.g. [1,1,2,3,3,4,5,6,6,6,6] should print 1 2 3 4 5 6.
3+
4+
#Approach 1: Using Sorting
5+
#Time-complexity: O(nlogn){of sorting},Auxiliary-space : O(1)
6+
7+
def print_distinct(a)
8+
n=a.length
9+
a.sort! #You can use any o(nlogn) sorting algorithm you wish
10+
i=0
11+
while i<n
12+
while (i<n-1 && a[i] == a[i+1])
13+
i+=1
14+
end
15+
print "#{a[i]} "
16+
i+=1
17+
end
18+
return
19+
end
20+
21+
print_distinct([4, 7, 4, 1, 1, 4, 8, 10, 6, 7]) # => 1 4 6 7 8 10
22+
23+
#Approach 2: Using Hashing
24+
#Time-complexity: O(n),Auxiliary-space:O(n) {for hash}
25+
26+
def print_distinct(a)
27+
n=a.length
28+
hash=Hash.new()
29+
for i in 0...n
30+
unless hash[a[i]]
31+
hash[a[i]]=1
32+
print "#{a[i]} "
33+
end
34+
end
35+
return
36+
end
37+
38+
print_distinct([4, 7, 4, 1, 1, 4, 8, 10, 6, 7]) # => 4 7 1 8 10 6

0 commit comments

Comments
 (0)