-2

As a part of my course work i need to calculate the complexity of programs. I'd like to calculate the space complexity and time complexity of the below program.How do i calculate it? It would be really helpful for me if somebody can explain it in detail.

sub find_multi_string {
    my ($file, @strings) = @_; 
    my $fh;
    open ($fh, "<$file");
    #store the whole file in an array
    my @array = <$fh>;

    for my $string (@strings) {
        if (grep /$string/, @array) {
            next;
        } else {
            die "Cannot find $string in $file";
        }   
    }   

    return 1;
}
  • People won't answer this question because they'd either have to be too specific to this problem, leaving you with no conceptual understanding of what's happening, or start right back at the basics, which are already explained well in many places, including online (and, presumably, in your course notes and lectures). It's definitely one of those things where it's worth finding some good reference material and investing time up front understanding it properly. – j_random_hacker Jul 08 '14 at 14:41

1 Answers1

0

Space complexity: Identify data that occurs "in large quantities" or "repeatedly". Assign numbers to these quantities, e.g., N = number of lines in a file, or M = number of elements in an array. Add these quantities. Watch out for the dynamic creation of data structures: if you have an array of N numbers and another one of M numbers and you create a table of all the products, then the space complexity of the table is...

Time complexity: Identify repeated actions. Some may be hidden (as in Perl), some are explicit, e.g. in a for loop. Use the results of space complexity to quantify these repetititions. A loop may be terminated early: then you must estimate the average time of execution. Loops occurring one after the other add up. If you know that a loop body is executed N times and this body contains an inner loop that executes M times, then the body of that inner loop is executed - how often?

Very frequently it's just a simple exercise of counting, bookkeeping and simple arithmetic, although there are several examples where a good answer requires heavy math.

Not in your case!

laune
  • 31,114
  • 3
  • 29
  • 42