Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find the lexicographically largest palindromic Subsequence of a String in Python
Sometimes we need to find the lexicographically largest palindromic subsequence of a string. A palindromic subsequence reads the same forwards and backwards, and the lexicographically largest one uses the highest character in the string.
The key insight is that the lexicographically largest palindromic subsequence consists of all occurrences of the maximum character in the string, since identical characters always form a palindrome.
So, if the input is like "tutorialspointtutorial", then the output will be "uu".
Algorithm Steps
To solve this, we will follow these steps −
Initialize ans as empty string
Find the maximum character in the string
Collect all occurrences of this maximum character
Return the result
Example
Let us see the following implementation to get better understanding −
def largest_palindromic_substr(s):
ans = ""
max_val = s[0]
# Find the maximum character in the string
for i in range(1, len(s)):
max_val = max(max_val, s[i])
# Collect all occurrences of the maximum character
for i in range(0, len(s)):
if s[i] == max_val:
ans += s[i]
return ans
s = "tutorialspointtutorial"
print(largest_palindromic_substr(s))
The output of the above code is −
uu
How It Works
In the string "tutorialspointtutorial", the algorithm first finds that 'u' is the lexicographically largest character. Then it collects both occurrences of 'u' to form "uu", which is indeed a palindrome and the lexicographically largest possible palindromic subsequence.
Alternative Approach Using Built-in Functions
We can simplify this using Python's built-in functions −
def largest_palindromic_substr_v2(s):
max_char = max(s)
return max_char * s.count(max_char)
s = "tutorialspointtutorial"
print(largest_palindromic_substr_v2(s))
uu
Conclusion
The lexicographically largest palindromic subsequence always consists of all occurrences of the maximum character in the string. This approach has O(n) time complexity and works efficiently for any input string.
