🥷 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
Solved LeetCode 1625 with BFS and modular arithmetic
More Relevant Posts
-
🚀 LeetCode Daily Challenge — 3726. Remove Zeros in Decimal Representation (Easy) Ever thought how a simple number like 1020030 can turn into 123? 🤔 That’s the power of string manipulation in programming — short, clean, and efficient! 💡 🧩 Problem Summary: You’re given a positive integer n. Your task: Remove all zeros from its decimal representation. Example: Input: n = 1020030 Output: 123 ✅ Hint: Convert the number to a string → remove all '0' → convert back to integer. That’s it — one-liner solution for clean data transformation. 🔥 💻 I’ve explained this problem with step-by-step approaches and code on my website 👉 algopush.com Check it out for brute force to optimized explanations! #LeetCode #LeetCodeChallenge #Coding #ProblemSolving #DSA #Programming #100DaysOfCode #CodeSeCareer #TechLearning #Developers #algopush #LeetCodeDaily #StringManipulation #LearnToCode #erdelhiboy #leetcodeeasy
To view or add a comment, sign in
-
-
🚀 Day 19/50 | LeetCode Coding Challenge Today's problem: Maximum Frequency After Operations - A challenging medium-level problem that tested my optimization skills! 💡 The Challenge: Given an array and k operations, we can add values in range [-k, k] to selected indices. The goal? Maximize the frequency of any element. 🎯 Key Learnings: 1️⃣ Binary Search Optimization: Replaced O(n²) nested loops with binary search using lower_bound/upper_bound - reduced complexity from O(n²) to O(n log n) 2️⃣ Two-Pointer Technique: Implemented sliding window to efficiently find valid ranges where elements can be transformed 3️⃣ Integer Overflow Awareness: Used long long for calculations with values up to 10⁹ to prevent overflow errors 4️⃣ Multiple Strategies: Combined two approaches: Keeping existing values unchanged Transforming all elements to a new target value ⚡ The Result: ✅ 633/633 test cases passed ✅ Time complexity: O(n log n) ✅ Optimized from TLE to accepted solution 🔥 Biggest Takeaway: When you hit Time Limit Exceeded, don't give up! Analyze your bottlenecks: Identify nested loops → Consider binary search or two pointers Watch for repeated computations → Use preprocessing Always handle edge cases (overflow, boundary conditions) The journey from brute force to optimal solution taught me more than just getting it right the first time ever could. Day 19 ✅ | 31 more days to go 💪 Shishir chaurasiya and PrepInsta #100DaysOfCode #CodingChallenge #LeetCode #DSA #ProblemSolving #SoftwareEngineering #CPlusPlus #Algorithms #TechJourney #LearningInPublic
To view or add a comment, sign in
-
-
💻 Day 15 of My 120 Days LeetCode Challenge 🚀 Problem: 3Sum (LeetCode #15) 🧩 Problem Statement: Given an integer array nums, the task is to find all unique triplets [nums[i], nums[j], nums[k]] such that: nums[i] + nums[j] + nums[k] == 0 and i, j, k are all different indices. If no such triplets exist, return an empty list. The output should not contain duplicate triplets. 🧠 Example: Input: nums = [-1, 0, 1, 2, -1, -4] Output: [[-1, -1, 2], [-1, 0, 1]] ⚙️ Approach / Algorithm Used: I solved this problem using the Two-Pointer Approach after sorting the array. 🔹 Steps: Sort the array to handle duplicates easily. Fix one element (nums[i]) and use two pointers — left and right. Move the pointers based on the sum: If sum < 0 → move left++ If sum > 0 → move right-- If sum == 0 → store the triplet and skip duplicates. Continue until all unique triplets are found. This method efficiently finds all possible triplets without repetition. 🕒 Time Complexity: O(n²) (because we fix one element and use two pointers for the rest) 💾 Space Complexity: O(1) (ignoring the output storage) ✅ Key Learning: Practiced handling duplicates in sorted arrays. Improved my understanding of two-pointer technique. Learned how to efficiently find triplets that satisfy given conditions. 🎯 #Day15 #LeetCodeChallenge #DSA #C++ #TwoPointer #ProblemSolving #CodingJourney #100DaysOfCode #LearnByDoing #Programming
To view or add a comment, sign in
-
-
🚀 Day 8 of #120DaysOfCode — String to Integer (atoi) 🧩 Today’s challenge was LeetCode Problem 8: “String to Integer (atoi)”, a classic string parsing problem that teaches how to handle input conversion safely and efficiently — something we often take for granted in programming. 🧠 Problem Summary: We need to implement the myAtoi(string s) function that converts a string into a 32-bit signed integer. The function must: Ignore leading whitespaces Handle optional + or - signs Extract the number until a non-digit is found Clamp (limit) the value within the 32-bit integer range Return the final integer result 📘 Example: Input → " -042" Output → -42 ⚙️ Approach I Used: I solved this problem using a step-by-step parsing approach: Trim spaces: Move through the string to skip leading whitespaces. Check the sign: If the next character is '-', mark the sign as negative, otherwise positive. Convert characters to digits: Loop through the characters while they are digits and build the result (result = result * 10 + digit). Handle overflow: Before updating the result, check if adding another digit would exceed the 32-bit integer range ([-2³¹, 2³¹ - 1]). Return the final value: Apply the sign and return the integer. This approach ensures correctness, prevents overflow, and follows a clean linear-time logic with O(n) complexity and O(1) space. 💡 Key Learning: Even a simple-looking task like string-to-integer conversion involves careful consideration of edge cases, boundaries, and input validation — all critical in real-world software systems. 💬 Next Goal: Continue improving my problem-solving skills with more logic-building and string manipulation challenges! #100DaysOfCode #120DaysOfCode #LeetCode #CProgramming #ProblemSolving #CodingChallenge #DeveloperJourney #LearningEveryday
To view or add a comment, sign in
-
-
💻 Day 3 of My #120DaysOfLeetCode Challenge 🚀 🧩 Problem: Longest Substring Without Repeating Characters Difficulty: Medium | Language Used: C 🔍 What’s the Problem About? The task is to find the length of the longest substring in a given string that contains no repeating characters. For example: Input: "abcabcbb" → Output: 3 (Longest substring: "abc") Input: "pwwkew" → Output: 3 (Longest substring: "wke") Input: "bbbbb" → Output: 1 (Longest substring: "b") This problem is a classic example of how we can optimize brute force logic using sliding window and two-pointer techniques. ⚙️ Approach I Used – Sliding Window Technique Instead of checking every possible substring (which would be very slow), I used a sliding window approach with two pointers (left and right) and a frequency array to track visited characters. Here’s the step-by-step thought process: Start both pointers at the beginning of the string. Move the right pointer one step at a time, adding characters to the window. If a character repeats, move the left pointer ahead until all characters in the window are unique again. Keep track of the maximum window size during the process. This ensures each character is processed only once → giving an efficient O(n) solution. 💡 Key Takeaways Learned how two-pointer and sliding window techniques can simplify substring problems. Understood how to use frequency arrays to track duplicates efficiently. Strengthened logical reasoning and window-based problem-solving skills in C. Every new problem is an opportunity to refine logic, enhance efficiency, and get one step closer to mastering Data Structures and Algorithms. Day 3 completed ✅ | 117 more to go 💪 #LeetCode #CProgramming #DSA #ProblemSolving #CodingChallenge #100DaysOfCode #LearningJourney #SlidingWindow
To view or add a comment, sign in
-
-
📌 Day 34/150 – Letter Combinations of a Phone Number (LeetCode #17) Today’s problem was a creative mix of recursion and backtracking, simulating how old phone keypads map digits to letters. ☎️ The challenge? Given a string of digits (2–9), generate all possible letter combinations that the digits could represent. At first, it looks like a simple mapping problem — just convert digits to letters. But the real task is to explore every possible combination of those letters in a systematic way. 🔹 Brute Force Idea Try every combination by using nested loops for each digit. ✅ Works for small inputs. ❌ Fails as the number of digits increases — leads to exponential growth in possibilities. 🔹 Optimal Approach – Backtracking (DFS) 👉 Key Insight: Treat each digit as a node and explore all possible letter choices for it recursively. Build combinations character by character until all digits are processed. At each step: Pick one letter from the current digit’s mapping. Recurse for the next digit. Backtrack to explore other possibilities. This ensures we cover all possible combinations efficiently and elegantly. 🧠 Example: Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] Here’s how it works: 2 → "abc" 3 → "def" We combine every letter from "abc" with every letter from "def". ⏱️ Time Complexity: O(3ⁿ × 4ᵐ) (since 7 & 9 have 4 letters each) 📦 Space Complexity: O(n) (recursion depth) 💡 Learning: Backtracking problems often feel complex, but they’re just structured explorations of possibilities. Once you visualize recursion as a decision tree, these problems become much easier to reason about. 🌳 #150DaysOfCode #LeetCode #ProblemSolving #Backtracking #Recursion #DSA #CodingChallenge #SoftwareEngineering #Cplusplus #Developers #LearningJourney #TechCommunity 🚀
To view or add a comment, sign in
-
-
🚀 Day 46 of 150 Days LeetCode Challenge #150DaysOfCode #LeetCode #CodingChallenge #DSA #HashMap #CPlusPlus #Programming #SoftwareEngineering #TechLearning #ProblemSolving #CodeDaily #LeetCode150DaysChallenge #Algorithm #DataStructures 🔹 Problem Statement:Contains Duplicate II Given an integer array nums and an integer k, check if there exist two distinct indices i and j in the array such that: nums[i] == nums[j] |i - j| <= k In simple words: “Does the array contain a duplicate within a distance of k?” 🔹 Example: Input: nums = [1,2,3,1], k = 3 Output: true Explanation: nums[0] and nums[3] are both 1, and the distance between them is 3 ≤ k. 🔹 Approach: Use a hash map to store each number with its most recent index. Iterate through the array: If the number already exists in the map, calculate the distance between the current index and the previous index. If this distance ≤ k, return true. Update the map with the current index. Return false if no such pair is found. Time Complexity: O(n) | Space Complexity: O(n) 🔹 Key Insights: ✅ Hash maps allow O(1) lookups for duplicates. ✅ Always update the index to track the most recent occurrence. ✅ Brute-force approaches take O(n²), but hash maps reduce it to O(n).
To view or add a comment, sign in
-
-
Don’t dive into LeetCode before you know this. It can save 40% of your time… 👇 I wasted weeks because I didn’t know this. What changed? 𝗜 𝗹𝗲𝗮𝗿𝗻𝗲𝗱 𝗖++ 𝗦𝗧𝗟 (𝗦𝘁𝗮𝗻𝗱𝗮𝗿𝗱 𝗧𝗲𝗺𝗽𝗹𝗮𝘁𝗲 𝗟𝗶𝗯𝗿𝗮𝗿𝘆). 🧠 Why it matters: STL saves you from writing complex data structures from scratch. Everything — from sorting to searching — is already optimized and tested. 𝗜𝘁 𝗵𝗮𝘀 𝟰 𝗺𝗮𝗶𝗻 𝗽𝗮𝗿𝘁𝘀: ➝ Containers (the data structures) ➝ Algorithms (the actions, like sort()) ➝ Iterators (the “pointers” that move through them) ➝ Functions (we’ll skip this for now) ⚡ 𝗟𝗲𝘁’𝘀 𝗱𝗶𝘃𝗲 𝗶𝗻𝘁𝗼 𝗖𝗼𝗻𝘁𝗮𝗶𝗻𝗲𝗿𝘀 — 𝗠𝗼𝘀𝘁 𝗨𝘀𝗲𝗱 (𝗶𝗻 𝗼𝗿𝗱𝗲𝗿): ➝ vector – dynamic array, most common → vector<int> v = {1,2,3}; ➝ unordered_map – fastest key-value lookups → unordered_map<string,int> mp; ➝ map – sorted key-value pairs ➝ set – unique sorted elements ➝ unordered_set – unique, unsorted, faster ➝ deque – insert/remove from both ends ➝ list – doubly linked list ➝ stack / queue / priority_queue – specific use (LIFO/FIFO) ➝ array – fixed size, static 💡 𝗤𝘂𝗶𝗰𝗸 𝗧𝗶𝗽𝘀: ➝ Use vector by default unless you have a reason not to. ➝ Use unordered_map when you need speed, map when you need order. ➝ set and unordered_set are perfect for unique elements. 📌 Save this post — you’ll need it every time you start a DSA problem 🚀 #cplusplus #stl #dsa #programming #codingjourney #developers #techstudents #leetcode #students #engineeringlife #competitiveprogramming
To view or add a comment, sign in
-
-
🚀 Day 22/30 – 30DaysOfDSAChallenge 🚀 🧠 Topic: Subsets (Power Set Generation) 📘 Concepts Covered: Recursion | Backtracking | Power Set Today I solved the Subsets problem, where the goal is to generate all possible combinations (subsets) of a given array. This problem is a classic example of recursive backtracking and helps in building a solid foundation for combinatorial logic. 🔹 Approach – Recursive Backtracking 💡 Logic: At each recursive step, decide whether to include or exclude the current element. When we reach the end of the array, one subset is complete and added to the result. This method explores 2ⁿ possible subsets efficiently. ⚙️ Time Complexity: O(2ⁿ) ⚙️ Space Complexity: O(2ⁿ * n) (for storing all subsets) ✅ Result: Accepted ✅ | Runtime: 0 ms 🟢 | Beats: 100% 🚀 ✨ Key Takeaway: Recursion becomes powerful when you break a problem into smaller, self-similar parts. Every inclusion or exclusion step leads you toward mastering backtracking and decision trees. #Day22 #30DaysOfDSAChallenge #LeetCode #Recursion #Backtracking #PowerSet #Subsets #ProblemSolving #CPlusPlus #CodingChallenge #DSA #Programming #CodeEveryday #DeveloperJourney #Algorithms
To view or add a comment, sign in
-
-
Day 26 of #50DaysLeetCodeChallenge 🧩 Problem: 561. Array Partition Today’s problem was a refreshing one — an Easy-level LeetCode challenge that reinforces how sorting and pairing can optimize outcomes. It’s one of those problems that looks simple but beautifully demonstrates the power of greedy algorithms. 🧠 Thought Process: 🔹 The task is to group integers into pairs such that the sum of the smaller element in each pair is maximized. 🔹 Sorting the array ensures each pair is as balanced as possible. 🔹 Once sorted, we simply take every alternate element (starting from index 0), since that will always represent the smaller element in each optimal pair. 🔹 This method eliminates unnecessary complexity and ensures maximum total sum. ⚙️ My Approach: 🔸 Sort the array using Arrays.sort(nums). 🔸 Initialize sum = 0. 🔸 Loop through the array with a step of 2, adding nums[i] to the sum each time. 🔸 Return the final sum — the maximum possible result. 📈 Performance: ✅ Accepted ⚡ Runtime: 17 ms (Beats 13.97%) 💾 Memory: Efficient and clean implementation 💡 Reflection: Sometimes, simplicity is the key to optimization. Even without complex data structures, understanding the problem’s core logic can lead to elegant solutions. Each day’s challenge sharpens both reasoning and coding clarity. Grateful to Trainer Shishir chaurasiya and PrepInsta for guiding me through consistent, concept-driven learning in DSA 🙏 #LeetCode #50DaysLeetCodeChallenge #ProblemSolving #Java #AlgorithmDesign #CodingChallenge #PrepInsta #DeveloperJourney #LogicBuilding #DSA #CleanCode #LearningEveryday
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