From 867399287f5ad7655a1315c2dc9ebd08e366b137 Mon Sep 17 00:00:00 2001 From: Deven <63876261+devenperez@users.noreply.github.com> Date: Wed, 26 Nov 2025 15:19:27 -0500 Subject: [PATCH] Time: 5673 ms (9.42%), Space: 17.8 MB (59.54%) - LeetHub --- .../0005-longest-palindromic-substring.py | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 0005-longest-palindromic-substring/0005-longest-palindromic-substring.py diff --git a/0005-longest-palindromic-substring/0005-longest-palindromic-substring.py b/0005-longest-palindromic-substring/0005-longest-palindromic-substring.py new file mode 100644 index 0000000..f5895c2 --- /dev/null +++ b/0005-longest-palindromic-substring/0005-longest-palindromic-substring.py @@ -0,0 +1,29 @@ +class Solution: + def longestPalindrome(self, s: str) -> str: + """ + Complexities: + Time: O(n^3) + Space: O(1) + + where n = len(s) + """ + + # indicies inclusive - O(n) + def isPalindrome(startIndex: int, endIndex: int): + if startIndex >= endIndex: + return True + + if s[startIndex] == s[endIndex]: + return isPalindrome(startIndex + 1, endIndex - 1) + return False + + + maxPalindrome = s[0] + for i in range(len(s)): + for j in range(i + 1, len(s)): + length = j - i + 1 + if length > len(maxPalindrome) and isPalindrome(i, j): + maxPalindrome = s[i:j+1] + + return maxPalindrome +