Longest Palindrome | Leet code 409 | Theory explained + Python code

preview_player
Показать описание
This video is a solution to Leet code 409, Longest Palindrome. I explain the question and the best way to solve it and then solve it using Python.

Comment below if you have a better solution to this problem!

Let me know if you have any feedback and don't forget to subscribe for more videos!

More leetcode questions solved:

Gear used:
Рекомендации по теме
Комментарии
Автор

excellent explanation, nice taught, keep it up bro

BevaraSateeshKumar
Автор

We won't need that conditional check on line 14 because our loop will handle the case where there is only 1 key value pair in our hash map.

FahadKhan-sizt
Автор

you can just combine the logic into one if/else block and use an if block outside the for loop to check if we can add one final odd character to the anagram count.

count = {}
for char in s:
if char in count:
count[char] += 1
else:
count[char] = 1

length = 0
odd = False

for freq in count.values():
#if the frequency is an even number, we can just add it to our total length
if freq > 1 and freq % 2 == 0:
length += freq
else:
length += freq-1
odd = True
#this final case deals with the possibility of adding a singular 'odd' count to middle of the anagram.
if odd:
length+=1

return length

this just makes more intuitive sense and the code is much cleaner.

rohitkavuluru
Автор

Not related to the above question. I need to ask what is the time complexity of itertools.combinations in python when we have n, r given (constant) and combinations(array of len n, r) is executed??

jyotijangid
Автор

what is the complexity of your code? I guess it's n^2. n^2 ? "Can we reduce it more" : "great"

SHIVAMKUMAR-dyqc
Автор

Hi Anish,

Thank you for explaining this solution in an easiest way. I want to mention one small thing, with the above solution, I was getting a KeyError: 'a' in line 9. But when I used 'try'-'except' in place of 'if-condition'(line 6-9) it worked for me. Thanks.

deepalisrivastava
Автор

Nice explanation!
I also want to say that you have a pretty voice

KhanhTran-vkkn
Автор

Thanks for sharing this approach! The solutions available at leetcode were kinda unreadable with 3 nested loops..

hassanrasoolsiddiqui