Solved LeetCode 1625 with BFS and modular arithmetic

🥷 Day 164 of My 365 LeetCode Challenge is done! 💥 Kicked off strong, solved my problem, and the coding vibe is awesome! 🧠 💡 LeetCode 1625 — Lexicographically Smallest String After Applying Operations Today’s challenge was an interesting blend of string manipulation, BFS traversal, and modular arithmetic — the kind of problem that truly sharpens both your algorithmic thinking and pattern recognition skills. 🧠✨ We’re given a numeric string s and two integers a and b. Two operations can be performed repeatedly in any order: 1️⃣ Add a to all digits at odd indices (with digits wrapping around modulo 10). 2️⃣ Rotate the string to the right by b positions. The goal? 🔍 Find the lexicographically smallest string possible after performing any number of these operations. Sounds simple, right? But here’s the catch — since operations can be performed infinitely, the problem hides a state-space exploration challenge. The same string can appear multiple times via different paths, so blindly iterating could easily lead to infinite loops or redundant computations. ⚙️ Approach & Thought Process: To systematically explore all possible transformations, I used Breadth-First Search (BFS) — perfect for enumerating all reachable states in minimal steps. 🔸 Step 1: Start from the original string and push it into a queue. 🔸 Step 2: For each string, perform both allowed operations: - Add a to digits at odd indices (handling digit wraparound using (digit + a) % 10). - Rotate the string by b positions. 🔸 Step 3: Use a set to track all previously visited strings to prevent cycles. 🔸 Step 4: Continuously compare and update the smallest lexicographic string seen so far. Once the queue is exhausted, the smallest recorded string is our answer ✅ 🔥 Key Learning: This problem elegantly demonstrates how graph traversal (BFS) can be applied beyond traditional graphs — even on state transformations of strings. Recognizing this pattern is a huge step toward mastering advanced algorithmic thinking. ✨ Every problem like this one is a reminder that great coding isn’t about memorizing — it’s about seeing structure where others see chaos. #LeetCode #CPlusPlus #CodingChallenge #ProblemSolving #Algorithms #BFS #SoftwareEngineering #Programming #LearningJourney #CodeNewbie #DataStructures

  • graphical user interface

To view or add a comment, sign in

Explore content categories