DEV Community

Ruairí O'Brien
Ruairí O'Brien

Posted on

Week 1 Bonus - Palindrome Permutation

I have the code for this in this GitHub Repo

The Problem

Leetcode Link

Given a string, determine if a permutation of the string could form a palindrome.

Example 1:

Input: "code"
Output: false
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: "aab"
Output: true
Enter fullscreen mode Exit fullscreen mode

Example 3:

Input: "carerac"
Output: true
Enter fullscreen mode Exit fullscreen mode

My Tests

import pytest
from .Week1Bonus import Solution

s = Solution()


@pytest.mark.parametrize("test_input", ["code", "abc"])
def test_cannot_permute(test_input):
    assert not s.canPermutePalindrome(test_input)


@pytest.mark.parametrize("test_input", ["aab", "carerac", "a", "aa"])
def test_can_permute(test_input):
    assert s.canPermutePalindrome(test_input)
Enter fullscreen mode Exit fullscreen mode

My Solution

class Solution:
    def canPermutePalindrome(self, s: str) -> bool:
        if len(s) == 1:
            return True
        char_counts = {}
        for c in s:
            if c in char_counts:
                char_counts[c] = char_counts[c] + 1
            else:
                char_counts[c] = 1
        values = char_counts.values()
        num_odd = 0

        for n in values:
            if n == 1 or n % 2 != 0:
                num_odd += 1

        return num_odd < 2
Enter fullscreen mode Exit fullscreen mode

Analysis

Alt Text

Alt Text

My Commentary

OK, I was pretty lazy with this one but it didn't turn out too terrible.

I thought if you go through the string and figure out how many letters appear an odd number of times, it was then a reasonable solution to check if we had more than one letter appearing an odd number of times. If we do then no permutation of the string can be a palindrome.

I have not put much thought into a better solution yet so if you have any tips please let me know :)

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay