AsadulloAbduev's blog

By AsadulloAbduev, history, 11 months ago, In English

In this problem limit for N is 1e5, but in 4th test says "time limit exceeded". Why? really 1 second isn't 1e8? This is my code:

#include <bits\stdc++.h>
#define vector vector
#define pb push_back
#define ll long long
#define ull unsigned long long
#define ld double
#define str string
#define yes cout << "YES"
#define no cout << "NO"

using namespace std;

ll mod = 1e9 + 7, MAX = 1e18, MIN = -1e18;
ld pi = 3.141592;

void solve()
{
    ll n, i;
    cin >> n;
    str s, x = "", ans = " ", y = "";
    cin >> s;
    s = '.' + s;
    for (i = 1; i <= n; i++){
        x += s[i];
        y = s[i] + y;
        ans = min(ans, x + y);
    }
    cout << ans;
} 

main()
{
///    setlocale(LC_ALL, "UTF-8");
///    freopen ("input.txt", "r", stdin);
///    freopen ("output.txt", "w", stdout);
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int t = 1;
    cin >> t;
    while (t --> 0){
        solve();
        cout << '\n';
    }
}

  • Vote: I like it
  • -24
  • Vote: I do not like it

»
11 months ago, # |
Rev. 2   Vote: I like it +18 Vote: I do not like it

$$$y=s[i]+y$$$ is $$$O(N)$$$ which is inside another for loop. So, your total TC is $$$O(N^2)$$$. Avoid string concatenation if possible.

»
11 months ago, # |
  Vote: I like it 0 Vote: I do not like it

your time complexity of code is not O(N). rather it is O(N^2) because you are doing ans = min(ans,x+y); due to which the minimum function will first concatenate the string x and y and then check for lexographically smallest string among (ans/x+y) which takes O(N), therefore total TC O(N^2).