TLE on My solution

So, I was solving a question and OJ accepted my answer partly, I guess this is because of the time complexity of my code but I'm unable to optimize it further. Here's the question:
Input: First line will contain an integer t, followed by t numbers of strings.Next line contains integer n followed by n number of queries consisting of r and spaced string p.

Output: contains single lexicographically smallest common prefix string.

example:
4
pfgh
pfgj
pfgji
pfgjik
2
3 pfgy
4 pfgji

Output
pfgh
pfgji

My code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
  #include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
 
string commonPrefix(string s1, string s2)
{
    string result;
    int n1 = s1.length(), n2 = s2.length();
 
    for (int i=0, j=0; i<=n1-1&&j<=n2-1; i++,j++)
    {
        if (s1[i] != s2[j])
            break;
        result.push_back(s1[i]);
    }
    return (result);
}
int main()
{
    long long n,q;
    int r;
    cin>>n;
    string str[n],pstr;
    for (int i=0; i<n; i++)
        cin>>str[i];
    cin>>q;
    while(q--)
    {
        cin>>r>>pstr;
        string prefix[r];
        for (int i=0; i<r; i++){
        prefix[i]=commonPrefix(str[i],pstr);
        }
      int index=0; string res=str[0]; int eleLen=prefix[0].length();
        for (int i=0; i<r; i++)
        {
         if(eleLen<prefix[i].length())
          {
              index=i;eleLen=prefix[i].length();
          }
          else if (eleLen == prefix[i].length())
          {
              if(str[index]>str[i])
              {
                  index=i;
              }
          }
        }
        res=str[index];
        cout<<res<<endl;
    }
    return 0;
 
}
 
I only recently started to use that site, but it seems possible to get Time Limit Expired (TLE) and your answer could still be wrong (WA). It just cuts off if the time is greater, not giving your program a chance to finish.

There was a recent explosion of threads asking for help on the June contest problems, so if you just browse other threads here you may learn some tips.

I'll tell you right now that straight-up arrays are too slow. Btw, why did you include <algorithm> ? You're not using anything from there...might help if you do.

I got 5/6 accepted and one answer threw some kind of SIGSEV runtime error, which got me questioning whether the input even matches the constraints.

@icy1 : Do you mean I should be using vectors instead?
try a trie or a tree.
also, http://www.cplusplus.com/reference/algorithm/lower_bound/

> n number of queries consisting of r and spaced string p
¿what's `r'?
r is number of strings till which it will check smallest LCP lexicographically
Topic archived. No new replies allowed.