in reply to Better algorithm or data structure?

Here's my stab at it, which goes along with what jethro and graff have already mentioned. %sets is kept as a hash for convenient deletes. By keeping track of which sets to update/delete once a resource ($next) becomes available, we only need to traverse a minimal amount of sets:
use Data::Dump qw[ pp ]; use List::Util qw[ shuffle ]; use Time::HiRes qw[ time ]; our $N //= 1e3; our $S //= 1e4; our $Z //= 5; my @bools; my %sets = map { my $s = $_; my $n = 1 + int( rand $Z ); ++$bools[ $_ ]{ $s } for map int( rand $N ), 1 .. $n; $s => $n; } 0 .. $S - 1; my @someOrder = shuffle 0 .. $N-1; my $start = time; for my $next ( @someOrder ) { for my $s (keys %{ $bools[ $next ] }) { $sets{ $s } -= delete $bools[ $next ]{ $s }; delete $sets{ $s } unless $sets{ $s }; } } printf "Took %.6f\n", time() - $start; pp \@bools; pp \%sets; __END__ Took 0.089563 [ {}, {}, ... ] {}

Update: FWIW, the OP code took around 20 seconds on my virtual machine running FreeBSD.