Approach
Breadth-first search
For Synonymous Sentences, 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
- 33 lines of Java from the credited upstream file 1258.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 4 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 List<String> generateSentences(List<List<String>> synonyms, String text) {3 Set<String> ans = new TreeSet<>();4 Map<String, List<String>> graph = new HashMap<>();5 Queue<String> q = new ArrayDeque<>(List.of(text));6 7 for (List<String> synonym : synonyms) {8 final String s = synonym.get(0);9 final String t = synonym.get(1);10 graph.putIfAbsent(s, new ArrayList<>());11 graph.putIfAbsent(t, new ArrayList<>());12 graph.get(s).add(t);13 graph.get(t).add(s);14 }15 16 while (!q.isEmpty()) {17 final String u = q.poll();18 ans.add(u);19 String[] words = u.split("\\s");20 for (int i = 0; i < words.length; ++i)21 for (final String synonym : graph.getOrDefault(words[i], new ArrayList<>())) {22 23 words[i] = synonym;24 final String newText = String.join(" ", words);25 if (!ans.contains(newText))26 q.offer(newText);27 }28 }29 30 return new ArrayList<>(ans);31 }32}33