Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: LeetCode Problem #1 - Two Sum - Improve and/or discuss.

by syphilis (Archbishop)
on Jan 24, 2022 at 06:02 UTC ( [id://11140777]=note: print w/replies, xml ) Need Help??


in reply to LeetCode Problem #1 - Two Sum - Improve and/or discuss.

use strict; use warnings; my @tests = ( [[2,7,11,15], 9, 0, 1], [[2,7,11,15], 9, 1, 0], [[3,2,4], 6, 1, 2], [[3,2,4], 6, 2, 1], [[3,3], 6, 0, 1], [[3,3], 6, 1, 0], [[3,3,3,3,3,1,3,2,3,3,3,3], 3, 5, 7], [[3,3,3,3,3,1,3,2,3,3,3,3], 3, 7, 5], [[7,7,9,2,8,7,4,2], 13, 2, 6], [[7,7,9,2,8,7,4,2], 13, 6, 2], ); my $count = 1; for(@tests) { my $ret = two_sum($_->[0], $_->[1]); #check the result for correctness. if( ($$ret[0] == $_->[2] && $$ret[1] == $_->[3]) || ($$ret[1] == $_->[2] && $$ret[0] == $_->[3]) ){ print "ok $count +\n" } else { print "@$ret\n"; print "not ok $count\n"; } $count++; } sub two_sum { my ($input, $target) = (shift, shift); # keep track of the original indices of the values, # prior to sorting the values. my %h; for(my $i = 0; $i < @$input; $i++) { # If the same value occurs twice, then # either they both form the solution, or # neither is part of the solution. # Any value that occurs more than twice # cannot be part of the solution. if(exists $h{$$input[$i]} ) { return [$h{$$input[$i]}, $i] if $target == $$input[$i] * 2; next; # not part of the solution and therefore # no need to test that value any further. } $h{$$input[$i]} = $i; } # Now let's sort the values. my @in = sort {$a <=> $b} keys(%h); my ($lo, $hi) = (0, @in - 1); for(;;) { # eliminate one value at each iteration my $cmp = ($in[$lo] + $in[$hi]) <=> $target; if ($cmp < 0) { $lo++ } elsif($cmp > 0) { $hi-- } else { # return the indices of the given values. return [ $h{$in[$lo]}, $h{$in[$hi]} ]; } # Safeguard against non-conforming inputs: die "Bad input array" if $lo >= $hi; } }
Cheers,
Rob

Update:
When I first looked at this challenge, I noticed that the values in the first example were ordered from lowest to highest - which enables the opportunity to halve the maximum number of trial additions that will be needed. (This could be quite a saving on lengthy arrays of values.)
So I went ahead and coded up a procedure that worked quite nicely on sorted arrays.
Then I noticed that there was no guarantee that the input arrays would be pre-sorted.

Ok ... I'll just have to sort the input array first. (And don't worry that the cost of doing that probably outweighs the advantage of reduced additions.)
And then I woke up to the fact that I had to return the indices of the 2 values, not the 2 actual values.
Ok ... I can pre-process the original input array so that I keep track of the indices of the values, and then return the appropriate index values.
While doing this, I can remove duplicates from the input array - so it's not all additional cost.

By the time I finished, I felt like the only man to not Escape from Stalag Luft 112B.
But I posted anyway - as testament to the dangers of obstinacy and determination ;-)

Replies are listed 'Best First'.
Re^2: LeetCode Problem #1 - Two Sum - Improve and/or discuss.
by ikegami (Patriarch) on Jan 25, 2022 at 14:43 UTC

    O(N log N), O(N) if already sorted.

    Rather than sorting the inputs, I would sort the indexes. That way, you wouldn't need an extra hash an array, just an array.

Re^2: LeetCode Problem #1 - Two Sum - Improve and/or discuss.
by kcott (Archbishop) on Jan 25, 2022 at 21:36 UTC

    G'day Rob,

    ++ Perhaps consider it in the positive light of professionalism and perseverance.

    I loved those Ripping Yarns shows when they came out in the mid to late '70s. From your link, I found others; further searching located the remainder. It looks like I've lined up several hours of Australia Day entertainment. :-)

    — Ken

      It looks like I've lined up several hours of Australia Day entertainment. :-)

      That sure is a lot more appealing than waving flags ;-)

      Cheers,
      Rob

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11140777]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2024-04-24 05:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found