Palindrome Permutation II (Leetcode 267) Solution - Coding Interview Question

Mani
Mani
Educating everyone with the beauty of programming!!

Given a string s, return all the palindromic permutations (without duplicates) of it.

You may return the answer in any order. If s has no palindromic permutation, return an empty list.

 

Example 1:

Input: s = "aabb"
Output: ["abba","baab"]

Example 2:

Input: s = "abc"
Output: []

 

Constraints:

  • 1 <= s.length <= 16
  • s consists of only lowercase English letters.

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
 * Approach: To construct a palindrome since all the input characters are used, we will generate the prefix permutations
 * and append the middle and do a reverse of prefix to get the suffix for the final string.
 * Palindrome = prefix + middle + (reverse of prefix)
 * Validation Check: If the number of characters with odd occurances > 1 we cannot form a palindrome with it since only one element can be the center .
 * So we do backtracking based on the hashmap count of chars.
 * Input is broken into half counts for each of the characters to generate prefix permutations.
 * Time Complexity: O((n/2 + 1)!)
 * Space Complexity: O(n)
 **/
class Solution {
    public List<String> generatePalindromes(String s) {
        Map<Character, Integer> map = new HashMap<>();

        for (char ch : s.toCharArray()) {
            map.merge(ch, 1, Integer::sum);
        }

        Character odd = null;
        //Detect chars with odd count.
        int oddCount = 0;
        for (Character ch : map.keySet()) {
            if (map.get(ch) % 2 == 1) {
                odd = ch;
                oddCount++;
            }
            //Reduce map count size to half for generating only prefix.
            map.put(ch, map.get(ch) / 2);
        }

        List<String> res = new ArrayList<>();
        if (oddCount > 1) {
            return res;
        }
        backtrack(res, s, odd, "", map);
        return res;
    }

    void backtrack(List<String> res, String s, Character odd, String cur, Map<Character, Integer> map) {
        if (cur.length() == s.length() / 2) {
            String middle = odd == null ? "" : odd + "";
            res.add(cur + middle + new StringBuilder(cur).reverse().toString());
            return;
        }

        for (Character ch : map.keySet()) {
            int count = map.getOrDefault(ch, 0);
            if (count != 0) {
                map.merge(ch, -1, Integer::sum);
                backtrack(res, s, odd, cur + ch, map);
                map.merge(ch, 1, Integer::sum);
            }
        }
    }

}
Drop your comments below for any questions or comments. For full list of must learn top interview questions Click Here: Must Learn Top Interview Questions

Rating: