Solving Lexicographically Smallest String with BFS and Graph Traversal

🚀 Day 40 / 100 — #100DaysOfLeetCode 💡 (1625) Lexicographically Smallest String After Applying Operations (Medium) This was a really fun graph + BFS problem disguised as a string manipulation challenge. The trick is realizing that applying the two operations (add & rotate) repeatedly explores a finite set of states, forming an implicit graph, where each node is a string transformation. 🧩 Problem Overview You are given: A numeric string s Two integers a and b You can repeatedly: Add a (mod 10) to all digits at odd indices. Rotate the string right by b positions. Find the lexicographically smallest string possible after any number of operations. ⚙️ Approach — BFS on States Used Breadth-First Search (BFS) to explore all reachable strings: Start from the initial string s. Use a set vis to track visited states. For each string, generate: One by performing addition on odd indices. One by rotating by b. Continue until all unique transformations are explored. Track the smallest lexicographical string seen. 📈 Complexities Time Complexity: O(10 * n) Each state can appear up to 10 times due to modulo operations, and each state has n length. Space Complexity: O(10 * n) For storing visited transformations. ✅ Key Insights The problem is finite because both operations are modular and cyclic. BFS guarantees we explore all possible reachable strings in an optimal manner. Lexicographical comparison after BFS is straightforward — track the smallest string so far. ✨ Takeaway This problem beautifully demonstrates how: “Even string problems can secretly be graph traversal problems.” It’s a neat mix of modular arithmetic, rotation logic, and state-space search. #LeetCode #100DaysOfCode #BFS #GraphTraversal #StringManipulation #ProblemSolving #Python #Algorithms

  • text

To view or add a comment, sign in

Explore content categories