Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re^4: Testing if an array contains a value and then deleting it in most efficient way

by parv (Parson)
on Feb 18, 2008 at 16:40 UTC ( [id://668600]=note: print w/replies, xml ) Need Help??


in reply to Re^3: Testing if an array contains a value and then deleting it in most efficient way
in thread Testing if an array contains a value and then deleting it in most efficient way

How can you avoid O(N^2) cost if using unsorted array? So far there is no indication whether it would be sorted. (Addendum: I wasn't thinking so just quoted the O(N^2) cost, which really should have been O(N). Time to sleep belatedly, I suppose.)

I thought that List::MoreUtils::firstidx would use XS magic (to avoid copying). No? (I would have looked inside the C code myself but am not familiar with XS yet.)

Later ... I see now that array might be already sorted (and first element would be the interesting one).

  • Comment on Re^4: Testing if an array contains a value and then deleting it in most efficient way

Replies are listed 'Best First'.
Re^5: Testing if an array contains a value and then deleting it in most efficient way
by ikegami (Patriarch) on Feb 18, 2008 at 16:50 UTC

    Update: No, I guess I'm wrong. The nested loops (while and firstidx confused me).


    while ( -1 < ( $i = firstidx { $_ == $val } @array ) ) { ... }

    is best case O(N).
    is worse case O(N2).

    for (0 .. $#array) { next if $_ != $var; ... }

    is best, real & worse case O(N).

      No, I was right.

      while ( -1 < ( $i = firstidx { $_ == $val } @array ) ) { ... }

      is worse case O(N2).

      Take the case where the condition is true for all items.
      For the first loop pass, all elements of @array are put on the stack ( time = k * N )
      For the second loop pass, all remaining elements of @array are put on the stack ( time = k * (N-1) )
      For the third loop pass, all remaining elements of @array are put on the stack ( time = k * (N-2) )
      ...
      For the last loop pass, all remaining element of @array is put on the stack ( time = k * 0 )

      The total time = k * ( N * (N+1) / 2 ) = O(N2)

      If the language evaluated @array lazily, it would be O(N).

        Note that OP did not say anything about handling of multiplicates. The inner loop is to delete all the matching values not just the first one, to be a similar solution to a hash solution (since the same key cannot occur multiple times).

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-04-24 07:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found