Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 266: Palindrome Permutation

LeetCode 266 Solution 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.

LeetCode 266 Solutions in Java, C++, Python

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;
}

Interactive Code Editor for LeetCode 266

Improve Your LeetCode 266 Solution

Use the editor below to refine the provided solution for LeetCode 266. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems