Understanding Algorithmic Complexity

I am considering some online algorithms for encoding interviews, and I do not understand why this algorithm is considered O (n ^ 3).

Caution: I understand that notation is heavily abused in industry, and when I refer to O (n), I use this notation to indicate the upper bound on the execution time of algorithms, which is common outside of academia in most places.

Search for the longest palindromic substring. A simple solution could be:

bool isPalindrome(std::string s) {
  if (s.length() <= 1) {
    return true;
  }

  if (s[0] == s[s.length() - 1]) {
    return isPalindrome(s.substr(1, s.length() - 2));
  } else {
    return false;
  }
}

std::string longestPalindrome(std::string s) {
  std::string max_pal = "";
  for (size_t i = 0; i < s.length(); ++i) {
    for (size_t len = 1; len <= s.length() - i; ++len) {
      std::string sub = s.substr(i,len);
      if (isPalindrome(sub)) {
        if (max_pal.size() < sub.size()) max_pal = sub;
      }
    }
  }
  return max_pal;
}

Is this algorithm O (n ^ 2)? It is very simple that it takes O (n ^ 2) to get all the substrings, and O (n) time to determine if it is a palindrome. Where n is the number of characters in the source string.

+6
4

O (n ^ 2)? , O (n ^ 2) O (n), , .

, , - O(n^3), , O(n), O(n^2 * C*n), O(n^3)


, O(n^4), isPalindrome() is O(n^2):

  • O(n), : 1 + 3 + 5 + ... + n-2, O(n^2) .
  • O(n^2) longestPalindrome() O(n^4).

( O(n) substr(). - )

+8

, O (n ^ 2) O (n). , O (n ^ 2) ( ) O (n). n ^ 2 * n = n ^ 3, O (n ^ 3).

+1

O (n ^ 2) ( O (n)) (O (n ^ 2)). O (n ^ 4).

+1

O (N ^ 4) - .

isPalindrome , , . , O (n).

0

All Articles