Given a string s, return all the palindromic permutations (without duplicates) of it. You may return the answer in any order. If s could not be arranged into a palindrome, return an empty list.
Example 1:
Input: s = "aabb"
Output: ["abba","baab"]
Example 2:
Input: s = "abc"
Output: []
Constraints:
1 <= s.length <= 16s consists of lowercase English letters.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The basic idea is to try every possible combination of letters from the input, and see if any of them form a palindrome. We'll generate all the arrangements and then check each one for palindrome-ness.
Here's how the algorithm would work step-by-step:
def palindrome_permutation_brute_force(input_string):
letter_counts = {}
for letter in input_string:
letter_counts[letter] = letter_counts.get(letter, 0) + 1
odd_counts = 0
middle_character = ''
for letter, count in letter_counts.items():
if count % 2 != 0:
odd_counts += 1
middle_character = letter
if odd_counts > 1:
return []
# Get characters to arrange for half of the palindrome
half_string_characters = ''
for letter, count in letter_counts.items():
half_string_characters += letter * (count // 2)
arrangements = set()
def generate_permutations(characters, current_permutation):
if not characters:
arrangements.add(current_permutation)
return
for i in range(len(characters)):
remaining_characters = characters[:i] + characters[i+1:]
generate_permutations(remaining_characters, current_permutation + characters[i])
generate_permutations(half_string_characters, '')
palindromes = []
for arrangement in arrangements:
potential_palindrome = arrangement + middle_character + arrangement[::-1]
# Check if the created string is a palindrome
if potential_palindrome == potential_palindrome[::-1]:
palindromes.append(potential_palindrome)
return list(palindromes)The goal is to find all unique palindromes we can make by rearranging the input string. We avoid generating duplicates by only considering each character count, and then building permutations in a specific order.
Here's how the algorithm would work step-by-step:
def palindrome_permutations_two(input_string):
character_counts = {}
for character in input_string:
character_counts[character] = character_counts.get(character, 0) + 1
odd_characters = []
for character, count in character_counts.items():
if count % 2 != 0:
odd_characters.append(character)
# Palindromes can only have one character w/ odd frequency
if len(odd_characters) > 1:
return []
middle_character = odd_characters[0] if odd_characters else ""
half_characters = []
for character, count in character_counts.items():
half_characters.extend([character] * (count // 2))
results = []
def backtrack(current_permutation, used_indices):
if len(current_permutation) == len(half_characters):
palindrome = current_permutation + middle_character + current_permutation[::-1]
results.append(palindrome)
return
for index in range(len(half_characters)):
if index not in used_indices:
# Avoid duplicates - only swap different characters
if index > 0 and half_characters[index] == half_characters[index - 1] and index - 1 not in used_indices:
continue
current_permutation += half_characters[index]
used_indices.add(index)
backtrack(current_permutation, used_indices)
used_indices.remove(index)
current_permutation = current_permutation[:-1]
# We keep track of indices to ensure permutations
backtrack("", set())
return results| Case | How to Handle |
|---|---|
| Null or empty string input | Return an empty list since there are no permutations to generate. |
| Input string with only one character | Return a list containing the single character string itself as it's trivially a palindrome permutation. |
| Input string with a length of two and not a palindrome | Return an empty list as no palindrome permutation is possible. |
| Input string with characters that appear an odd number of times (more than one such character) | Return an empty list because palindrome permutation is impossible if there are more than one character with an odd count. |
| Input string containing only one distinct character repeated multiple times | Generate a list containing only that string since all permutations are the same and a palindrome. |
| Input string with extreme length approaching memory limits | Ensure the algorithm's memory usage is efficient; consider using iterative approach if recursion causes stack overflow for very long strings. |
| Input string with non-alphanumeric characters | Preprocess the string to either remove or normalize non-alphanumeric characters based on problem definition, or return an error if invalid. |
| Input string results in large number of permutations exceeding output list capacity | The algorithm needs to handle a large number of possible permutations without memory exhaustion, so consider optimization and algorithm efficiency. |