File tree Expand file tree Collapse file tree 1 file changed +49
-2
lines changed
chapter10/10.08 - Find Duplicates Expand file tree Collapse file tree 1 file changed +49
-2
lines changed Original file line number Diff line number Diff line change 1- // sort numbers
2- // stream through numbers and print elements which is a duplicate of the immediate previous number
1+ // We're given 4 kilobytes (4 * 2^10 * 8 = 32*2^10 bits) of main memory(RAM) to write a program to print all duplicate entries in an array
2+ // from 1 to N where N is at most 32,000 (32*2^10).
3+
4+ // We can use an Int8Array that uses 1 Byte per element to store 0's if we haven't seen it and 1's if we have seen it.
5+ // The Int8Array typed array represents an array of twos-complement 8-bit signed integers.
6+ // 4 KB > 32,000 bits
7+
8+ // Time Complexity - O(n)
9+ // Space Complexity - O(n)
10+
11+ // Let's have a JavaScript Solution of this program:
12+
13+ function FindDuplicates ( arr , range = 32000 ) {
14+ // Initialize integer 8 bit array with 0's at every index
15+ const numbersSeen = new Int8Array ( range ) ;
16+ const duplicates = [ ] ;
17+ for ( let i = 0 ; i < arr . length ; i ++ ) {
18+ if ( numbersSeen [ arr [ i ] ] === 0 ) {
19+ numbersSeen [ arr [ i ] ] = 1 ;
20+ } else {
21+ duplicates . push ( arr [ i ] ) ;
22+ }
23+ }
24+ return duplicates ;
25+ }
26+
27+ const arr = [
28+ 0 ,
29+ 1 ,
30+ 1 ,
31+ 2 ,
32+ 4 ,
33+ 6 ,
34+ 7 ,
35+ 9 ,
36+ 9 ,
37+ 34 ,
38+ 56 ,
39+ 78 ,
40+ 90 ,
41+ 101 ,
42+ 345 ,
43+ 789 ,
44+ 999 ,
45+ 999 ,
46+ 11000
47+ ] ;
48+ FindDuplicates ( arr ) ;
49+ // [1, 9, 999]
You can’t perform that action at this time.
0 commit comments