Approach
Breadth-first search
For Reorganize String, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 38 lines of Java from the credited upstream file 767.java.
- The implementation visibly relies on hash lookup, ordered lookup, work queue.
- 3 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public String reorganizeString(String s) {3 Map<Character, Integer> count = new HashMap<>();4 int maxFreq = 0;5 6 for (final char c : s.toCharArray())7 maxFreq = Math.max(maxFreq, count.merge(c, 1, Integer::sum));8 9 if (maxFreq > (s.length() + 1) / 2)10 return "";11 12 StringBuilder sb = new StringBuilder();13 14 Queue<Pair<Integer, Character>> maxHeap =15 new PriorityQueue<>(Comparator.comparing(Pair::getKey, Comparator.reverseOrder()));16 int prevFreq = 0;17 char prevChar = '@';18 19 for (final char c : count.keySet())20 maxHeap.offer(new Pair<>(count.get(c), c));21 22 while (!maxHeap.isEmpty()) {23 24 final int freq = maxHeap.peek().getKey();25 final char c = maxHeap.poll().getValue();26 sb.append(c);27 28 29 if (prevFreq > 0)30 maxHeap.offer(new Pair<>(prevFreq, prevChar));31 prevFreq = freq - 1;32 prevChar = c;33 }34 35 return sb.toString();36 }37}38