I recenty started solving questions on leetcode and came accross this Questions where we had to remove all alphanumeric characters from a string and then check if the string is a palindrome or not. I tried to keep O(n) time complexity still it took 54 ms which is way too long can someone please explain. Here is the code:
class Solution {
public:
bool isPalindrome(string s) {
int n = 0;
transform(s.begin(),s.end(),s.begin(),::tolower);
while(s[n] != '\0'){
if(isalnum(s[n]) == 0 ){
s.erase(s.begin()+n);
}
else{
n++;
}
}
string check = s;
reverse(s.begin(),s.end());
if(s == check){
return true;
}
else{
return false;
}
}
};
I was wanted to know what part of code exaclty is taking time
dsa
. Thedsa
tag is forDigital Signature Algorithm
.erase
by itself is an O(n) operation, and you have put that inside an O(n) loop. Therefore your code is actually O(n^2).std::remove_if
, plus know thaterase()
has an overload that takes abegin
andend
iterator, you would not have written the loop that callserase
on every individual character you want to erase.