Problem solution · Java

Palindrome Permutation II

Palindrome Permutation II: a Java solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
59 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Palindrome Permutation II, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 59 lines of Java from the credited upstream file 267.java.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
  • 5 loop blocks detected, together with recursive traversal.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codePalindrome Permutation II · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public List<String> generatePalindromes(String s) {    int odd = 0;    Map<Character, Integer> count = new HashMap<>();     for (final char c : s.toCharArray())      count.merge(c, 1, Integer::sum);     // Count odd ones.    for (Map.Entry<Character, Integer> entry : count.entrySet())      if (entry.getValue() % 2 == 1)        ++odd;     // Can't form any palindrome.    if (odd > 1)      return new ArrayList<>();     List<String> ans = new ArrayList<>();    List<Character> candidates = new ArrayList<>();    StringBuilder mid = new StringBuilder();     // Get the mid and the candidates characters.    for (Map.Entry<Character, Integer> entry : count.entrySet()) {      final char key = entry.getKey();      final int value = entry.getValue();      if (value % 2 == 1)        mid.append(key);      for (int i = 0; i < value / 2; ++i)        candidates.add(key);    }     // Backtrack to generate the ans strings.    dfs(candidates, mid, new boolean[candidates.size()], new StringBuilder(), ans);    return ans;  }   // Generates all the unique palindromes from the candidates.  private void dfs(List<Character> candidates, StringBuilder mid, boolean[] used, StringBuilder sb,                   List<String> ans) {    if (sb.length() == candidates.size()) {      ans.add(sb.toString() + mid + sb.reverse().toString());      sb.reverse();      return;    }     for (int i = 0; i < candidates.size(); ++i) {      if (used[i])        continue;      if (i > 0 && candidates.get(i) == candidates.get(i - 1) && !used[i - 1])        continue;      used[i] = true;      sb.append(candidates.get(i));      dfs(candidates, mid, used, sb, ans);      sb.deleteCharAt(sb.length() - 1);      used[i] = false;    }  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗