prepbook
  • Introduction
  • Some common stuff
    • python __repr__
    • HackerRank input tips
  • Data Structures and Algorithms
    • Breadth first search
    • Depth First Search
    • Dijkstra
    • A* Search Algorithm
    • Binary Search
    • python counter
    • Sorting
      • Merge Sort
      • Quick Sort
    • Priority Queue
  • Multiprocessing vs Threading
  • Common Coding
    • Find loop in lin list
    • Maximum sum subarray
  • Coding
    • Valid palindrome
    • Palindrome number
    • Remove duplicates from sorted array
    • Island perimeter
    • Serialize and Deserialize Binary Tree
    • Valid Soduku
    • Word Pattern
    • Word Pattern II
    • Group Anagrams
    • Implement Trie
    • Deep copy list with random node
    • Palindrome Permutation
    • Combination Sum
    • Clone Graph
    • Generate parenthesis
    • Fibonacci Number
    • LRU Cache
    • Merge two sorted arrays in place
    • Hamming Distance
    • Merge K sorted arrays
    • Kth smalles element in BST
    • Kth largest element in an array
    • Remove duplicates from sorted list
    • Power of 2
    • Nested list weight sum
    • SIngle number in a list
    • Factor combinations
    • Delete node from BST
  • hacker Rank
    • Coding
      • print staircase
      • Drawing book
      • Challenge 0
      • Min-Max sum
  • WorkRelatedCoding
    • Rectangle Overlap
  • Python tips
Powered by GitBook
On this page

Was this helpful?

  1. Coding

Palindrome Permutation

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

For example, "code"-> False,"aab"-> True,"carerac"-> True.

Hint:

  1. Consider the palindromes of odd vs even length. What difference do you notice?

  2. Count the frequency of each character.

  3. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?

class Solution(object):
    def canPermutePalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if not s:
            return False

        dict = {}

        for idx, elem in enumerate(s):
            if elem not in dict:
                dict[elem] = 1
            else:
                dict[elem] += 1

        if len(s) % 2 == 0: # even length string
            for elem, cnt in dict.iteritems():
                if cnt % 2 != 0:
                    return False
        else: # odd length string; will allow only one char to be odd
            cntOddElem = 0
            for elem, cnt in dict.iteritems():
                if cnt % 2 != 0:
                    cntOddElem += 1

            if cntOddElem > 1:
                return False

        return True
class Solution(object):
    def canPermutePalindrome(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if not s:
            return False

        dict = {}
        for idx, elem in enumerate(s):
           if elem not in dict:
                dict[elem] = 1
            else:
                dict[elem] += 1

        cntOddElem = 0
        for elem, cnt in dict.iteritems():
            if cnt % 2 == 1 and len(s) % 2 == 0: # even number of elements in string
                return False
            elif cnt % 2 == 1 and len(s) % 2 == 1: # odd number of elements in string
                cntOddElem += 1

        if cntOddElem:
            return (cntOddElem == 1)

        return True
PreviousDeep copy list with random nodeNextCombination Sum

Last updated 5 years ago

Was this helpful?