Kashyap Kale’s Post

View profile for Kashyap Kale, graphic

CS Grad @ Virginia Tech | Ex-Amazon, Tray | AI, LLMs, Algorithms, AWS, REST APIs, OOP

🚀 LeetCode Daily Problem Explanation for June 4th! 🚀 -- These are my accepted solutions, I would appreciate any optimisations in the comments !! -- 📝 Problem: Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome. 🏷️ Tag : Easy 🔍 Examples: Example 1: Input: s = "abccccdd" Output: 7 Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. Example 2: Input: s = "a" Output: 1 Explanation: The longest palindrome that can be built is "a", whose length is 1. 💡 Intuition A simple observation can be made: for a string to form a palindrome, all characters should have even counts, or all characters should have even counts except for one character that can have an odd count. 🛠️ Approach 1️⃣ Count the frequency of each character in the string using two arrays: one for lowercase letters and one for uppercase letters. 2️⃣ Calculate the number of characters that have an odd count. 3️⃣ If there are no characters with an odd count, the length of the longest palindrome is the length of the string. 4️⃣ If there are characters with odd counts, the length of the longest palindrome is the length of the string minus the number of odd counts plus one (since we can place one odd character in the center). ⏲️ Complexity Time complexity: 𝑂(𝑛) O(n), where 𝑛 is the length of the string. We iterate over the string to count character frequencies and then iterate over the counts. Space complexity: 𝑂(1) O(1), because the space used for the frequency arrays is constant (52 elements). -- Follow Kashyap Kale for daily code explanations -- #Coding #Programming #Algorithm #Tech #SoftwareEngineering #Developer #CodeNewbie #LinkedInTech #ProblemSolving #DSA #interviews #Cpp

  • graphical user interface, text
Swayam Terode

Founding SDE at Cad and Cart | NextJs | React Native 📱 | AWS

7mo

Here's my approach: Use HashSet and check for each char whether it is present in HashSet if true count++ and remove current char from HashSet else add current char in HashSet Once you have iterated the string check if HashSet is not Empty? If yes return count*2+1 else return count * 2 Hnadles both Lowercase and Uppercase scenarios. This is single pass solution. Where TC is O(N) And SC is O(N) for HashSet. Your Solution uses 2 pass which is O(N+N) which is O(2N)= O(N) and space also O(N) or rather it's O(1) because it is using 26 chars. Thanks learned new approach of solving this question.

To view or add a comment, sign in

Explore topics