Problemi in Duplicated Usernames

Ciao a tutti. Sto da un po’ cercando di risolvere il problema Duplicated Username, ma sto riscontrando delle difficoltà nell’esecuzione nelle task 3 (solo Execution Killed) e 4 (sia Time limit exceeded che Execution Killed). Qualcuno riuscirebbe a darmi un’indizio sul problema? Grazie

// NOTE: it is recommended to use this even if you don't understand the following code.

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    // uncomment the two following lines if you want to read/write from files
    // ifstream cin("input.txt");
    // ofstream cout("output.txt");

    string S;
    cin >> S;
    
    int N;
    cin >> N;
    
    vector<string> U(N);
    for (int i = 0; i < N; ++i)
        cin >> U[i];
    
    string T = "";
    
    
    // INSERT YOUR CODE HERE
    sort(U.begin(), U.end());
    string name, temp;
    bool uguale;
    int num;
    vector<int> num_util;
    
    for (int i=0; i<N; i++) {
    	name = U[i];
    	uguale = true;
    	
    	if (name.size() >= S.size()) {
    		for (int j=0; j<S.size(); j++) {
	    		if (name[j] != S[j]) {
	    			uguale = false;
					break;
				}
			}
		} else {
			uguale = false;
		}
		
		if (uguale) {
			if (name.size() == S.size()) {
				num = -1;
			} else {
				temp = "";
				for (int j=S.size(); j<name.size(); j++) {
					temp += name[j];
				}
				num = stoi(temp);
			}
			num_util.push_back(num);
			
		} else if (num_util.size() != 0) {
			break;
		}
	}
	
	sort(num_util.begin(), num_util.end());
	
    if (num_util[0] != -1) {
		T = S;
	} else {
		int i=1;
		while (count(num_util.begin(), num_util.end(), i) != 0) {
			i ++;
		}
		
		T = S + to_string(i);
	}
    
    cout << T << endl;

    return 0;
}