Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Simple Perl Interview Question
#perl 5.22.1 # find all common numbers in array1 and array2 and print them out @array1 = (4, -1, 5, 3, 9, -2, 1, 0, 10, 6); @array2 = (8, 3, -4, 5, 2, 1, 7, -1, -9); # Method 1 foreach in array2 lookup in array1 # Time complexity T(N*M) print "Method 1\n"; foreach $num2 (@array2) { foreach $num1 (@array1) { if ($num2 == $num1) { print "$num2\n"; } } } # Method 2 sort array1 and array2, scan from begining to the end # Time complexity O(NlogN + MlogM + N + M) print "Method 2\n"; @sorted1 = sort {$a <=> $b} @array1; @sorted2 = sort {$a <=> $b} @array2; $i = $j = 0; while ($i <= $#array1 && $j <= $#array2) { if ($sorted1[$i] == $sorted2[$j]) { print "$sorted1[$i]\n"; $i++; $j++; } elsif ($sorted1[$i] < $sorted2[$j]) { $i++; } else { $j++; } } # Method 3 using hashmap # Time complexity O(N + M) print "Method 3\n"; %dict = (); for $num1 (@array1) { $dict{$num1} = 1; } for $num2 (@array2) { if (defined($dict{$num2})) { print "$num2\n"; } }
run
|
edit
|
history
|
help
0
Anchal 101712
Lol
Lol
hashes
1st code
Palindromic Dates
testing dereference of anonymous routines
Lieta 101733
Attractive Numbers
Sanjana 101742