LeetCode 266: Palindrome Permutation Solution

Master LeetCode problem 266 (Palindrome Permutation), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

266. Palindrome Permutation

Problem Explanation

Explanation

To determine if a given string can be rearranged into a palindrome, we can count the frequency of each character in the string. For a string to be a palindrome, there can be at most one character with an odd frequency (the middle character). All other characters should have an even frequency.

We will iterate over the characters in the string, maintaining a count of the frequencies of each character. If we encounter a character whose frequency is already odd, we decrement its count, making it even. If we encounter a character with an even frequency, we increment its count, making it odd. Finally, we check if there is at most one character with an odd frequency.

Solution Code

public boolean canPermutePalindrome(String s) {
    int[] charFreq = new int[128];
    int oddCount = 0;
    
    for (char c : s.toCharArray()) {
        charFreq[c]++;
        if (charFreq[c] % 2 == 0) {
            oddCount--;
        } else {
            oddCount++;
        }
    }
    
    return oddCount <= 1;
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 266 (Palindrome Permutation)?

This page provides optimized solutions for LeetCode problem 266 (Palindrome Permutation) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 266 (Palindrome Permutation)?

The time complexity for LeetCode 266 (Palindrome Permutation) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 266 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 266 in Java, C++, or Python.

Back to LeetCode Solutions