🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gfWSucCh 💡 My thought process: This solution calculates the minimum cost to change a `source` string into a `target` string using allowed substring transformation rules that have specific costs. The transformations form a weighted directed graph, where each substring is a node, and each transformation is an edge with a cost. To manage indirect transformations effectively, Dijkstra’s algorithm finds the shortest path between two substrings. Since the same substring conversions can be requested multiple times, the algorithm saves the shortest-path results to avoid repeating graph searches. The overall solution employs top-down dynamic programming, with each state showing the minimum cost to transform the string starting from a given index. If the characters at the current position match, the algorithm moves forward at no cost. If they do not match, it examines all valid substring lengths and adds the transformation cost to the result of the remaining suffix. This mix of dynamic programming, shortest-path computation, and saved results ensures both accuracy and efficiency. 👉 My Solution: https://lnkd.in/gCv3cXCf If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
Min Cost String Transformation with Dijkstra's Algorithm
More Relevant Posts
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/g6C9kJb4 💡 My thought process: For a specific value of k, there are exactly 2^k possible binary strings of that length. For example, if k = 2, the possible binary codes are 00, 01, 10, and 11, making a total of 4 combinations. The solution uses a sliding window approach with size k. It goes through the string using index j and keeps adding characters to a temporary string called window. When the size of the window equals k, the substring is added to an unordered set to ensure it is unique. After adding, the window shifts forward by removing its first character using substr(1), and the process continues. At the end, the function checks if the number of unique substrings stored in the set equals 1 shifted left by k, which represents 2^k. If the sizes match, it means every possible binary substring of length k is in the string, and the function returns true. If not, it returns false. The time complexity is O(n × k) because each substring operation can take up to O(k) time. The space complexity is O(2^k) in the worst case for storing all possible substrings. 👉 My Solution: https://lnkd.in/gBrK8uHB If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gwdQDKx4 💡 My thought process: The code calculates the sum of all root-to-leaf paths in a binary tree where each node contains either 0 or 1. Each path from root to leaf represents a binary number. The goal is to convert these binary numbers to decimal and return their total sum. The helper function solve performs a depth-first search. It builds a binary string along the current path by adding the node’s value. When a leaf node is reached, the binary string is saved in a vector. The recursion continues for the left and right children until all root-to-leaf paths are explored. In sumRootToLeaf, after collecting all binary path strings, each string is converted to its decimal equivalent using bit shifting. For each character, its value is multiplied by the corresponding power of 2 and added to a running total. The final result is the sum of all converted values. The time complexity is linear based on the number of nodes, and additional space is needed for recursion and storing path strings. 👉 My Solution: https://lnkd.in/gwAHXfX6 If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gChbc9pi 💡 My thought process: Use an Array to store the values of the tree. The inorder function performs an inorder traversal of the original BST, collecting all node values into a list. Since the inorder traversal of a BST visits nodes in ascending order, the values list is sorted automatically. The buildTree function recursively constructs a balanced BST from a range [left, right] of the sorted values list. The base case returns null when left is greater than right, indicating that the range is empty. For each range, we find the middle index and create a node with values[mid]. This middle element becomes the root of the current subtree. We then recursively build the left subtree using elements from left to mid-1, and the right subtree using elements from mid+1 to right. This method maintains balance because at each level, we split the remaining elements into roughly equal parts. The time complexity is O(n) for the inorder traversal and O(n) for building the tree, resulting in O(n) overall. The space complexity is O(n) for storing values and O(log n) for the recursion stack depth of a balanced tree. 👉 My Solution: https://lnkd.in/gxBj8v6b If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gXwweaP3 💡 My thought process: This solution finds the longest substring where the characters 'a', 'b', and 'c' appear the same number of times. It approaches the problem by breaking it into three separate cases: substrings with one character, substrings with two distinct characters, and substrings with all three characters. In the single-character case, the method scans the string and tracks the length of the longest continuous run of the same character. This addresses substrings where balance is easily met, as only one character is present. For the two-character case, the technique uses a prefix-difference approach. While scanning the string, it counts the two selected characters and calculates their difference. If the same difference has occurred before, the segment between the last index and the current index must have equal counts of the two characters, making its length a valid option. When a third character appears, it resets the counts and the hash map to prevent invalid matches across segments. In the three-character case, the prefix concept is extended to two dimensions. Instead of tracking one difference, the algorithm focuses on two differences: (count(a) − count(b)) and (count(a) − count(c)). If the pair of differences appears again, it indicates that the counts of all three characters between those indices are equal, creating a balanced substring. A hash map keeps the earliest index for each difference pair, allowing for quick length updates in a single pass through the string. 👉 My Solution: https://lnkd.in/gc_vMxFG If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gw_xVvrb 💡 My thought process: For the best approach, i am using a lambda function where we are performing sorting based on the number of set bits in the number. We are using the built-in popcount function in C++ to count the number of set bits in a given number. If the set bits are the same, return the smaller number in that scenario. You can use extra space like an ordered map to make it simpler; that code is available on my GitHub. 👉 My Solution: https://lnkd.in/g8x_PxTh If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
Day 52 - LeetCode Journey Solved LeetCode 11: Container With Most Water (Medium) today using the Two Pointer approach. This journey isn’t about solving the hardest problems daily, but about showing up consistently and improving step by step. Problems like this help in building a deeper understanding of how optimization actually works. Today’s problem reinforced key concepts like: • Using two pointers to reduce time complexity • Understanding how width and height affect area • Moving the pointer with smaller height for better results • Avoiding brute force and thinking optimally The key idea is simple — start from both ends and move intelligently to maximize the area 💡 Every problem adds a new layer to problem-solving skills, and that’s where real growth happens 💯 ✅ Better understanding of two-pointer technique ✅ Improved optimization thinking ✅ More confidence in DSA concepts Still a long way to go, but progress is progress 🚀 #LeetCode #DSA #Java #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #Algorithms #Programming #DeveloperJourney #KeepCoding
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/g4J85qey 💡 My thought process: If you have a block of three 0s followed by a block of two 1s (00011), you can only create two valid pairs: 01 and 0011. The smaller group always limits the number of matches you can make, which is why the code uses min(prev, curr). To keep track of this, the code uses prev for the size of the block you just finished and curr for the block you’re currently counting. As you go through the string, you keep increasing curr as long as the characters remain the same. The moment the character changes, like when you hit a 1 after a series of 0s, it means you've completed a block. You take the min of the old block and the new block, add it to your total, move the curr count into prev, and start over for the next group. There is one small issue in the code: because that addition only happens when the characters change, the very last block in the string doesn't get processed inside the loop. That’s why there is one extra result += min(prev, curr) at the very end to catch that final transition. 👉 My Solution: https://lnkd.in/gdK35f76 If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 Day 7/60 — LeetCode Discipline Problem Solved: Contiguous Array (Revision) Difficulty: Medium Today’s practice focused on identifying equal 0s and 1s in a binary array using prefix sum and hashmap optimization. Revisiting this problem reinforced how transforming the problem space can unlock efficient linear-time solutions. 💡 Focus Areas: • Strengthened prefix sum transformation technique • Practiced hashmap-based frequency tracking • Improved subarray pattern recognition • Focused on writing clean and efficient logic ⚡ Performance Highlight: Achieved solid runtime performance on submission. Quiet consistency, deeper patterns, sharper intuition. #LeetCode #60DaysOfCode #100DaysOfCode #DSA #PrefixSum #HashMap #Algorithms #DataStructures #ProblemSolving #CodingJourney #SoftwareEngineering #TechCareers #Programming #Developers #CodingLife
To view or add a comment, sign in
-
-
I wrote my first LeetCode solution. Not for points. For thinking. Most DP answers jump to code. That confused me. So I stopped copying. I started explaining. Why? Because DP isn’t formulas. It’s decisions. I learned the thinking from Raj Vikramaditya. Then rewrote it in my own words. From scratch. From intuition. Not recursion → tabulation blindly. But why each step exists. Process 🔁: • Took Striver’s DP pattern • Started from raw intuition • Logged every decision • Converted thought → recursion • Then recursion → tabulation Result? A solution that shows thinking. Not just syntax. If you’ve done Striver’s DP, you’ll feel this instantly. If you haven’t, this helps you start right. Link in comments. Built for learners, not flex. Follow if you value thinking over template solutions 🔔 Link - https://lnkd.in/gtMUbirm #DynamicProgramming #LeetCode #DSA #ProblemSolving #SoftwareEngineering #LearningInPublic #StriverDP #InterviewPrep #ComputerScience
To view or add a comment, sign in
-
-
Day 12/60 – LeetCode Challenge 🚀 Problem: Maximum Product Subarray Today’s concept: Handling Negative Numbers in Dynamic Programming 💡 Unlike Maximum Subarray Sum (Kadane), this problem is tricky because of NEGATIVE numbers. Why? Because: Negative × Negative = Positive 🔁 So at every index, the minimum product so far can suddenly become the maximum if multiplied by a negative number. My Approach (Based on My Code): I maintained three variables: • minBestending → Minimum product ending at current index • maxBestending → Maximum product ending at current index • result → Overall maximum product Initialization: minBestending = nums[0] maxBestending = nums[0] result = nums[0] For every element from index 1: I calculated three values: v1 = nums[i] v2 = prevMin * nums[i] v3 = prevMax * nums[i] Then: minBestending = min(v1, v2, v3) maxBestending = max(v1, v2, v3) Finally: result = max(result, maxBestending) Key Insight 🔥 At every step, we must track BOTH: • Current maximum product • Current minimum product Because the minimum might turn into maximum after multiplying with a negative number. Time Complexity: O(n) Space Complexity: O(1) Major Learning: Whenever: • Negative numbers are involved • Product based optimization is required • Sign flipping is possible Think beyond normal Kadane. Track both min and max. Day 12 completed ✅ Consistency > Motivation 🚀 #LeetCode #DSA #DynamicProgramming #Java #CodingJourney #PlacementPreparation
To view or add a comment, sign in
-
Explore related topics
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