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';
}
}
$$$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.
ok
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).