I did not benchmark this yet - but this should be faster (it passes your tests):
sub twosum_NetWallah{ my ($inp, $target)=@_; my %targ_idx = map { $inp->[$_] => $_ } 0..$#$inp; for (0..$#$inp){ next unless defined ( my $other=$targ_idx{ $target - $inp->[$_] } + ); next if $other == $_; return [ $other > $_ ? ($_, $other) : ($other, $_) ]; } return undef; } # Test NetWallah.. for my $test (@tests) { is_deeply sort_arrayref(twosum_NetWallah ($test->[INPUT], $test->[TARGET +])), sort_arrayref($test->[EXPECTED]); }
UPDATE 1: removed buggy " -1" from (0..$#$inp -1); deleted unnecessary variable @solutions.

UPDATE 2: I did try to benchmark the code - kcott's runs ~ 40% faster, so I was surprised!
However- After adding this test case:

[[-5,-3,1,4,7], 1, [1,3]],
kcott's code fails that test case, but mine passes.
Note - that new test case does meet the problem definition (array of integers), which can have negative numbers.
Also - kcott's code assumes and takes advantage of the input being sorted - input order is NOT specified in the problem definition.

BTW - thanks for setting up this challenge!

                "If you had better tools, you could more effectively demonstrate your total incompetence."


In reply to Re: LeetCode Problem #1 - Two Sum - Improve and/or discuss. by NetWallah
in thread LeetCode Problem #1 - Two Sum - Improve and/or discuss. by kcott

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.