'What is the time complexity of the longestPalindrome function in the following code?

size_t length(const pair<size_t, size_t>& pos) { 
    return pos.second - pos.first; 
} 
 
pair<size_t, size_t> longestPalindrome(const string& s, size_t start, size_t end, map<pair<size_t, size_t>, pair<size_t, size_t>>& memo) { 
    if (memo.find({start, end}) != memo.end()) { 
        return memo[{start, end}]; 
    } 
     
    if (end - start == 1) { 
        return {start, end}; 
    } 
     
    if (end - start == 2) { 
        if (s[start] == s[end - 1]) { 
            return {start, end}; 
        } 
        return {start, end - 1}; 
    } 
     
    if (s[start] == s[end - 1]) { 
        auto p = longestPalindrome(s, start + 1, end - 1, memo); 
        if (p.first == (start + 1) && p.second == (end - 1)) { 
            return memo[{start, end}] = {start, end}; 
        } 
    } 
     
    auto p1 = longestPalindrome(s, start + 1, end, memo); 
    auto p2 = longestPalindrome(s, start, end - 1, memo); 
     
    return memo[{start, end}] = (length(p1) > length(p2) ? p1 : p2);     
}

The above function finds the longest substring that is also a palindrome.

Given a string, the code starts with two pointers: one at the start, and one at the end. If the character on these two positions are not the same, longestPalindrome recursively calls itself, once by incrementing start and once by decrementing end.

If it were not for the memoization, the function would have been O(2^n). But now that I'm using a memo, what is the time complexity of this code?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source