Approach
Depth-first search
For Lexicographically Smallest String After Applying Operations, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 36 lines of Java from the credited upstream file 1625.java.
- The implementation visibly relies on hash lookup, ordered lookup.
- 1 loop block 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.
Use this to learn the idea, then write your own version.
1class Solution {2 public String findLexSmallestString(String s, int a, int b) {3 ans = s;4 5 dfs(s, a, b, new HashSet<>());6 7 return ans;8 }9 10 private String ans;11 12 private void dfs(String s, int a, int b, Set<String> seen) {13 if (seen.contains(s))14 return;15 16 seen.add(s);17 if (ans.compareTo(s) > 0)18 ans = s;19 20 dfs(add(s, a), a, b, seen);21 dfs(rotate(s, b), a, b, seen);22 }23 24 private String add(final String s, int a) {25 StringBuilder sb = new StringBuilder(s);26 for (int i = 1; i < sb.length(); i += 2)27 sb.setCharAt(i, (char) ('0' + (s.charAt(i) - '0' + a) % 10));28 return sb.toString();29 }30 31 private String rotate(final String s, int b) {32 final int n = s.length();33 return s.substring(n - b, n) + s.substring(0, n - b);34 }35}36