🚀 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
Solving Lexicographically Smallest String with BFS and Graph Traversal
More Relevant Posts
-
🧩 Day 29 — 3Sum Closest (LeetCode 16) 📝 Problem Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. 🔁 Approach -Sort the array to use the two-pointer technique effectively. -Iterate through each element nums[i] (except the last two) and treat it as the first element of the triplet. -For each i, set two pointers: -left = i + 1 -right = len(nums) - 1 -Compute the sum of the three numbers: -total = nums[i] + nums[left] + nums[right] -If total == target, return total immediately (perfect match). -Otherwise, compare the absolute difference between total and target to update the closestSum. -Adjust pointers: -If total < target, move left pointer right to increase sum. -If total > target, move right pointer left to decrease sum. -Continue until all triplets are checked. -Return the final closestSum. 📊 Complexity -Time Complexity: O(n²) -Space Complexity: O(1) 🔑 Concepts Practiced -Sorting and two-pointer pattern -Optimization using sorted array and pointer movement -Handling duplicates efficiently -Absolute difference comparison for closest value #Leetcode #python #DSA #Sorting #problemSolving
To view or add a comment, sign in
-
-
🌙 Day 41 of LeetCode Challenge Problem: 1625. Lexicographically Smallest String After Applying Operations Difficulty: 🟠 Medium 🧩 Problem Summary: We are given a numeric string s (even length) and two integers a and b. We can: 1️⃣ Add a to all digits at odd indices (mod 10). 2️⃣ Rotate the string to the right by b positions. The goal is to find the lexicographically smallest string possible after performing these operations any number of times. 💡 Approach: The problem is based on exploring all possible transformations of the string. Since both operations can be applied infinitely, we use BFS (Breadth-First Search) to systematically try every possible state of the string. At each step: Apply the “add to odd indices” operation. Apply the “rotate by b” operation. Add new unique strings to a queue for further exploration. We also keep track of the smallest string found so far. The process continues until all possible states are explored. 🧠 Key Insights: There are only a finite number of unique strings possible because digits wrap around (mod 10) and rotations eventually repeat. BFS ensures we don’t miss any possible transformation. The smallest string is found naturally during the traversal. 🕹 Example: Input → s = "5525", a = 9, b = 2 After applying multiple add and rotate operations, the smallest string obtained is "2050". ⏱ Complexity: Time Complexity: O(10 × n²) Space Complexity: O(n × 10) 🔥 Takeaway: This problem beautifully combines string manipulation, mathematical operations, and graph traversal (BFS). Even simple operations can lead to complex state spaces — mastering how to explore them systematically is the key! #LeetCode #Day41 #Python #BFS #StringManipulation #CodingJourney 🚀
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 83 Problem: Minimum Possible Length of Original String from Concatenated Anagrams 🔡✨ This was an elegant string manipulation and frequency-matching problem — a beautiful blend of observation and brute-force validation. 🧠 Problem Summary: You are given a string s, known to be a concatenation of anagrams of some original string t. The task is to determine the minimum possible length of t. ✅ Each substring of length len(t) should contain exactly the same frequency of characters. ✅ The string s can thus be divided into equal-length chunks, all being anagrams of t. ✅ The goal is to find the smallest such length that satisfies this property. ⚙️ My Approach: 1️⃣ Iterate through all divisors i of n = len(s) — potential lengths of t. 2️⃣ For each possible i, check if the string can be divided into equal parts where each part has identical character frequencies. 3️⃣ Use hash maps to store frequency counts and compare each block. 4️⃣ Return the smallest i that satisfies the condition. 📈 Complexity: Time: O(n²) → Checking frequency for each valid divisor. Space: O(k) → For storing character counts per block. ✨ Key Takeaway: When tackling anagram-based problems, frequency comparison is your strongest ally. Instead of guessing patterns, rely on structure and repetition to reveal the hidden base string. 🔍 🔖 #DSA #100DaysOfCode #LeetCode #ProblemSolving #StringManipulation #Anagram #Python #CodingChallenge #InterviewPrep #EfficientCode #HashMap #DataStructures #TechCommunity #CodeEveryday #LearningByBuilding
To view or add a comment, sign in
-
-
Day 72: Partition List 🔗 I'm back to linked lists on Day 72 of #100DaysOfCode by solving "Partition List." The challenge is to rearrange a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x, while preserving the original relative order within each partition. My solution uses a two-list approach with dummy nodes: Creation of Two Lists: I initialize two separate dummy nodes: less_dummy and greater_dummy. Partitioning: I iterate through the original list once. If a node's value is less than x, I append it to the less list; otherwise, I append it to the greater list. This inherently preserves the relative order within each group. Merging: After the single pass, I set the next pointer of the tail of the less list to the head of the greater list (less_tail.next = greater_dummy.next). Crucially, I set the tail of the greater list to None to prevent cycles (greater_tail.next = None). This single-pass method achieves an optimal O(n) time complexity and O(1) extra space complexity (excluding the new nodes being rearranged). My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #LinkedList #100DaysOfCode #ProblemSolving
To view or add a comment, sign in
-
-
🧩 Day 30 — 4Sum (LeetCode 18) 📝 Problem -Given an integer array nums, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: -a, b, c, and d are distinct indices -nums[a] + nums[b] + nums[c] + nums[d] == target -Return the answer in any order. 🔁 Approach -Sort the array to handle duplicates efficiently. -Use a recursive k-sum approach that generalizes 2-sum, 3-sum, and 4-sum problems. -For k > 2, recursively reduce the problem: -Fix one number and call kSum for k - 1 on the remaining array. -Skip duplicates to avoid repeating quadruplets. -For k = 2, use the two-pointer technique: -Move pointers inward based on the sum comparison with the target. -Add valid pairs to the result and skip duplicates. -Backtrack after each recursive call to explore all possible combinations. 📊 Complexity -Time Complexity : O(n³) -Space Complexity : O(k) 🔑 Concepts Practiced -Recursive K-Sum pattern -Two-pointer technique -Sorting and duplicate handling -Backtracking with controlled search space #python #DSA #4Sum #ProblemSolving #Leetcode
To view or add a comment, sign in
-
-
🚀 Day 39/100 – Find Common Elements in Three Sorted Arrays Today I learned how to find the common numbers in three sorted arrays using an efficient approach. 🧠 Problem Statement: Given three sorted arrays, find the elements that are common in all three. 💻 Example: # Three sorted arrays arr1 = [1, 5, 10, 20, 40, 80] arr2 = [6, 7, 20, 80, 100] arr3 = [3, 4, 15, 20, 30, 70, 80, 120] # Output: [20, 80] ⚙️ Approach: ✅ Use three pointers (one for each array). ✅ Move pointers smartly to compare elements. ✅ If all three are equal → add to result. ✅ If not, move the pointer of the smallest value forward. 🧩 Code: def findCommon(arr1, arr2, arr3): i = j = k = 0 common = [] while i < len(arr1) and j < len(arr2) and k < len(arr3): if arr1[i] == arr2[j] == arr3[k]: common.append(arr1[i]) i += 1 j += 1 k += 1 elif arr1[i] < arr2[j]: i += 1 elif arr2[j] < arr3[k]: j += 1 else: k += 1 return common print(findCommon(arr1, arr2, arr3)) 🎯 Output: [20, 80] 💡 Key Takeaway: Efficient pointer logic can save both time and space complexity, especially when dealing with sorted data. #100DaysOfCode #Day38 #Python #DSA #LearningEveryday #CodingChallenge #Arrays
To view or add a comment, sign in
-
DAY-1:CODING CHALLENGE 1.Longest common Prefix substring from given string as input 2.3SUM problem Started with BRUTE-FORCE → checked every triplet. 😀 Worked 😇 but SLOW for big arrays (O(n³)) → TIME LIMIT EXCEEDED. Faced errors along the way: 'int object not iterable' → I wrote sorted(a,b,c) instead of sorted([a,b,c]). 'unhashable type: list' → Tried adding list to set. Fixed by converting to tuple. LOGICAL BUG → Return inside the loop returned early. Fixed by moving return outside. Finally moved to OPTIMAL TWO-POINTER APPROACH: Sort array first. Use two pointers to find pairs for target -nums[i]. Skip duplicates carefully. Complexity reduced to O(n²). 💡 Lessons learned: small syntax mistakes can cause big errors, immutable types are key for sets, and proper pointer logic makes code efficient. #Python #Algorithms #LeetCode #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 57: Binary Tree Zigzag Level Order Traversal 🎢 I'm continuing my journey with an advanced tree traversal problem on Day 57 of #100DaysOfCode: "Binary Tree Zigzag Level Order Traversal." The challenge is to return the nodes of a binary tree level by level, alternating the direction of traversal (left-to-right, then right-to-left, and so on). My solution builds upon the standard Breadth-First Search (BFS) algorithm, using a queue (deque): Level Traversal: I process the tree level by level, finding the level_size in each iteration. Direction Toggle: I use a boolean flag (left_to_right) to track the current direction. Zigzag Logic: Inside the level loop, I use a simple conditional: if left_to_right is true, I append the node value normally. If it's false, I insert the node value at the beginning of the current level's list (current_level.insert(0, node.val)). Optimal Flip: After processing the entire level, I flip the left_to_right flag (left_to_right = not left_to_right) for the next level. This single-pass BFS approach ensures all nodes are visited exactly once, achieving an optimal O(n) time complexity and O(n) space complexity. My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #Trees #BFS #100DaysOfCode #ProblemSolving #Zigzag
To view or add a comment, sign in
-
-
🌈 Understanding the Dutch National Flag Algorithm (Step-by-Step) Today, I explored one of the most elegant sorting algorithms — the Dutch National Flag problem, also known as the 3-way partitioning algorithm. 💡 Problem Statement: Given an array containing only 0s, 1s, and 2s — sort it without using any sorting function. Instead of counting or using extra space, we use three pointers: low → marks boundary of 0s mid → current element high → marks boundary of 2s 📊 Approach: 1️⃣ If arr[mid] == 0 → swap with arr[low], move both forward 2️⃣ If arr[mid] == 1 → just move mid forward 3️⃣ If arr[mid] == 2 → swap with arr[high], move high backward 🚀 This algorithm sorts the array in a single pass — O(n) time and O(1) space complexity. ✨ Final sorted array: [0, 0, 1, 1, 2, 2] This logic is not only efficient but also forms the foundation for partition-based algorithms like QuickSort. #Coding #Python #Csharp #Java #Algorithms #ProblemSolving #DataStructures #DutchNationalFlag #InterviewPreparation
To view or add a comment, sign in
-
-
🚀 DSA Progress – Day 106 ✅ Problem #557: Reverse Words in a String III 🧠 Difficulty: Easy | Topics: String, Two Pointers, In-place Reversal 🔍 Approach: Implemented a two-pointer traversal method to reverse each word in the sentence individually without changing the word order. Step 1 (Conversion): Since Python strings are immutable, first convert the input string into a list to allow in-place modifications. Step 2 (Traversal): Use pointer i to find the start of a word and pointer j to find its end by moving forward until a space or end of the string is found. Step 3 (Reversal): Once the word boundaries (i to j-1) are identified, reverse that portion in place using slicing (s[i:j] = reversed(s[i:j])). Step 4 (Iteration): Continue scanning until the entire sentence is processed. Finally, join the list back into a string and return it. This method ensures that each word’s characters are reversed, while their overall positions remain unchanged in the sentence. 🕒 Time Complexity: O(n) — Each character is visited once. 💾 Space Complexity: O(n) — For the list representation of the string. 📁 File: https://lnkd.in/gdefC89D 📚 Repo: https://lnkd.in/g8Cn-EwH 💡 Learned: This problem reinforced how two-pointer logic and in-place modification can be used to efficiently handle string problems. It also highlighted the importance of mutable vs immutable data types in Python. Breaking the sentence word by word made the logic clean and modular — a good reminder that even simple problems can sharpen control-flow and boundary-handling skills. ✅ Day 106 complete — flipped every word inside out but kept the sentence standing tall! ✨🪞📜 #LeetCode #DSA #Python #Strings #TwoPointers #InPlace #CodingJourney #InterviewPrep #DailyPractice #GitHubJourney
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development