<?xml version="1.0" encoding="windows-1252"?>
<node id="1007973" title="finding strings" created="2012-12-09 06:51:17" updated="2012-12-09 06:51:17">
<type id="115">
perlquestion</type>
<author id="659963">
duyet</author>
<data>
<field name="doctext">
Hello monks,

Someone sent me a link to www.interviewstreet.com and i tried one of those challenges called: [https://www.interviewstreet.com/challenges/dashboard/#problem/4efa210eb70ac|Find strings] for fun. I have submitted a working code but after 3 tests it fails with "Out of Memory"

I have tried a few attempts without real improvement, it gets a bit faster but still fails. Maybe you can have a look at it and let me know which parts can be improved.

TIA

&lt;code&gt;
Inputs:
2
aab
aac
3
3
8
24

Output:
aab
c
INVALID


#!/usr/bin/perl

use strict;
use warnings;

$| = 1;     # flush output

# Get inputs
my $n = 0;        # number of strings
chomp( $n = &lt;STDIN&gt; );

my $i = 0;      # line counter
my $w = '';     # input string
my @S = ();     # uniq strings from inputs
while ( $i++ &lt; $n )
{
    chomp ( $w = &lt;STDIN&gt; );
    push @S, get_uniq_strings( $w );
}

# Get the queries
my $q = 0;
chomp( $q = &lt;STDIN&gt; );

$i          = 0;
my $k       = '';
my @queries = ();
while ( $i++ &lt; $q )
{
    chomp( $k = &lt;STDIN&gt; );
    push @queries, $k - 1;
}

# Output
@S = make_uniq( \@S );
my $uniq_len = scalar @S;
foreach ( @queries )
{
    print (( $_ &lt;= $uniq_len ) ? "$S[ $_ ]\n" : "INVALID\n" );
}

exit;


sub get_uniq_strings
{
    my $string = shift;

    my @a = ();
    my $len = length $string;
    for ( my $i = 1; $i &lt;= $len; $i++ )
    {
        for ( my $offset = 0; $offset &lt; $len - $i + 1; $offset++ )
        {
            my $sub_str = substr $string, $offset, $i;
            push @a, $sub_str if $sub_str;
        }
    }

    @a;
}

sub make_uniq
{
    my $str_array = shift;

    my $uniq_array = {};
    foreach( @{ $str_array } )
    {
        $uniq_array-&gt;{ $_ }++ if $_;
    }

    sort keys %{ $uniq_array };
}
&lt;/code&gt;</field>
</data>
</node>
