Tap here to switch tabs
Problem
Submissions
Solution

Solution: Longest Palindromic Substring

Statement

Naive approach

A naive approach to this problem is to find all possible substrings and select one longest palindromic substring. For example, consider the string “deed”, which contains 10 substrings: “d”, “e”, “e”, “d”, “de”, “ee”, “ed”, “dee”, “eed”, and “deed”. Out of these 10 substrings, six are palindromes: “d”, “e”, “e”, “d”, “ee”, and “deed”. Among these palindromes, the longest palindromic substring is “deed”.

We get the required result, but at what cost? Since we’re checking every possible substring, the total number of substrings in a string of length nn is O(n2)O(n^2). The time required to check whether a string is a palindrome is O(n)O(n). Therefore, the time complexity of this algorithm is O(n3)O(n^3). Since we’re not using any extra space, the space complexity of this algorithm is O(1)O(1) ...

Tap here to switch tabs
Problem
Submissions
Solution

Solution: Longest Palindromic Substring

Statement

Naive approach

A naive approach to this problem is to find all possible substrings and select one longest palindromic substring. For example, consider the string “deed”, which contains 10 substrings: “d”, “e”, “e”, “d”, “de”, “ee”, “ed”, “dee”, “eed”, and “deed”. Out of these 10 substrings, six are palindromes: “d”, “e”, “e”, “d”, “ee”, and “deed”. Among these palindromes, the longest palindromic substring is “deed”.

We get the required result, but at what cost? Since we’re checking every possible substring, the total number of substrings in a string of length nn is O(n2)O(n^2). The time required to check whether a string is a palindrome is O(n)O(n). Therefore, the time complexity of this algorithm is O(n3)O(n^3). Since we’re not using any extra space, the space complexity of this algorithm is O(1)O(1) ...