🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/djbQcgTX 💡 My thought process: Problem is same as the before, the constraints are just a bit higher. We store the current values in temp (as long long) and simulate deletions using prevIndex/nextIndex as a doubly linked list, so after merging/removing an element we can find and update neighbors in O(1) without shifting the array. All current adjacent pairs are kept in an ordered set as (pairSum, leftIndex), which gives the minimum-sum adjacent pair in O(1) (begin()) and supports updates in O(log n). When we merge the chosen pair (first, second), only pairs involving first_left–first and second–second_right can change, so we erase those (if they exist), relink pointers to remove second, update temp[first] += temp[second], and insert the new affected pairs. We also maintain badPairs (count of adjacent inversions) and update it using only local comparisons around the merge boundary, since no other adjacencies are affected. Bad pairs will never increase than n-1. 👉 My Solution: https://lnkd.in/dcxVVSjV 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
LeetCode Challenge: Doubly Linked List Merge
More Relevant Posts
-
🚀 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/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
-
-
𝗗𝗮𝘆 38 𝗼𝗳 𝟯𝟲𝟬 days of LeetCode Challenge. 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 :- 3721. Longest Balanced Subarray II You are given an integer array nums. A subarray is called balanced if the number of distinct even numbers in the subarray is equal to the number of distinct odd numbers. Return the length of the longest balanced subarray. 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗹𝗶𝗻𝗸:- https://lnkd.in/djmqAqhd 𝗛𝗶𝗻𝘁:- 1.Think in terms of a sliding left boundary and maintain a prefix “balance” of distinct odd vs distinct even values; when the left boundary moves past the first occurrence of a value, adjust the balance only until its next occurrence. 2. Use a segment tree with lazy propagation over prefix balances so you can range-update efficiently and query the rightmost index where the balance becomes zero (i.e., a balanced subarray). 𝗚𝗶𝘁𝗵𝘂𝗯 𝗰𝗼𝗱𝗲:- https://lnkd.in/d-kxnEU4 #SoftwareEngineering #DSAJourney #Coding #LeetCode #DSA #TechCareers #SDE
To view or add a comment, sign in
-
-
🔢 String Pattern Recognition: Count Binary Substrings! 🚀 I'm excited to share my latest LeetCode success! Today, I tackled the "Count Binary Substrings" problem, passing all 91 test cases with a highly memory-efficient solution. 💡 The Strategy: Group-Based Counting Instead of a complex nested search, I focused on the core property of balanced binary substrings—they consist of consecutive '0's followed by an equal number of '1's (or vice-versa). Grouping Logic: I tracked the length of consecutive character groups (e.g., "00111" becomes groups of 2 and 3). * Linear Calculation: For any two adjacent groups, the number of valid substrings they can form is simply the minimum of the two group lengths. Space Optimization: By only keeping track of the prevGroup and currGroup lengths, I maintained a lean memory footprint of 12.84 MB, beating 96.95% of submissions! 🧠⚡ 📊 Performance Summary: Memory: 12.84 MB (Beats 96.95%) Runtime: 3 ms (passing all cases efficiently) This problem was a great reminder that re-framing a problem—from "finding substrings" to "measuring adjacent groups"—can lead to much more elegant and efficient code. Check out the full implementation and my daily progress on GitHub: 📂 Repository: https://lnkd.in/gZ2v73xh #LeetCode #DSA #CPP #StringAlgorithms #ProblemSolving #SoftwareEngineering #CodingLife #Efficiency #TechGrowth #DailyCoding
To view or add a comment, sign in
-
-
LeetCode Daily | Day 38 🔥 LeetCode POTD – 3714. Longest Balanced Substring II (Medium) ✨ 📌 Problem Insight A substring is balanced if all distinct characters in it appear the same number of times. String contains only 'a', 'b', 'c'. So a balanced substring can have: • 1 distinct character • 2 distinct characters (equal count) • 3 distinct characters (all equal count) 🔍 Approach Instead of one complex solution, split into 3 structured cases: 1️⃣ Mono (Single Character) • Longest consecutive same character • Always balanced 2️⃣ Duo (Two Characters) • Treat one char → +1 • Other char → −1 • Use prefix sum + hashmap • Reset when third character appears 👉 If two prefixes have same delta → equal count substring found. 3️⃣ Trio (Three Characters) • Maintain counts of a, b, c • Track (b−a, c−a) differences • If same pair appears again → balanced substring 👉 Same prefix-difference trick, extended to 2D. 💡 Why This Works Balanced condition reduces to: • For 2 chars → equal frequency • For 3 chars → equal pairwise differences Prefix differences repeating ⇒ middle substring is balanced. Breaking problem into structural cases simplifies implementation. ⏱ Complexity Time: O(n log n) (due to map) Space: O(n) (Can be optimized to O(n) using unordered_map) 🧠 Pattern Used Prefix Sum | Hashing | Difference Tracking | Case-Based Decomposition Clean structure > complicated logic. Hard part isn’t idea — it’s handling all cases correctly. Consistency over motivation — one problem a day 🚀 #LeetCode #DSA #PrefixSum #Hashing #Cplusplus #CodingDaily #Consistency
To view or add a comment, sign in
-
-
🚀 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
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gxntCVfP 💡 My thought process: I used Dijkstra’s algorithm to find the minimum cost path because all edge weights are non-negative. To manage edge reversals, I modeled the graph by adding: - the original directed edge with cost w - a reverse edge with cost 2w, which represents the reversal operation This converts the problem into a standard shortest-path graph, eliminating the need for extra state handling. An adjacency list and a min-heap priority queue make traversal efficient, while a visited array tracks the minimum cost to reach each node. This method is straightforward, efficient, and works well for large graphs. 👉 My Solution: https://lnkd.in/gBkufJ5G 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
-
-
𝗗𝗮𝘆 32 𝗼𝗳 𝟯𝟲𝟬 days of LeetCode Challenge. 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 :- 3013. Divide an Array Into Subarrays With Minimum You are given a 0-indexed array of integers nums of length n, and two positive integers k and dist. The cost of an array is the value of its first element. For example, the cost of [1,2,3] is 1 while the cost of [3,4,1] is 3. You need to divide nums into k disjoint contiguous subarrays, such that the difference between the starting index of the second subarray and the starting index of the kth subarray should be less than or equal to dist. In other words, if you divide nums into the subarrays nums[0..(i1 - 1)], nums[i1..(i2 - 1)], ..., nums[ik-1..(n - 1)], then ik-1 - i1 <= dist. Return the minimum possible sum of the cost of these subarrays. 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗹𝗶𝗻𝗸:- https://lnkd.in/gZAdyJcZ 𝗛𝗶𝗻𝘁:- For each index i, calculate a new circular index by shifting i by nums[i] steps, using modulo arithmetic to handle both positive and negative offsets. Populate the result array by fetching the value at each calculated index, ensuring the logic wraps around the array boundaries correctly. 𝗚𝗶𝘁𝗵𝘂𝗯 𝗰𝗼𝗱𝗲:- https://lnkd.in/giSfinNu #SoftwareEngineering #DSAJourney #Coding #LeetCode #DSA #TechCareers #SDE
To view or add a comment, sign in
-
-
𝟒 𝐂𝐨𝐧𝐜𝐞𝐩𝐭𝐬 𝐘𝐨𝐮 𝐌𝐮𝐬𝐭 𝐊𝐧𝐨𝐰 𝐢𝐧 𝐜𝐨𝐫𝐞 𝐉𝐚𝐯𝐚🔍 ☑️ 1. What is an Anonymous Class? It’s a local class without a name, declared and instantiated in a single expression. Use Cases: Perfect for event listeners in GUI apps (like ActionListener in Swing) or when you need a quick, one-off implementation of an interface/abstract class. ☑️2. What is a Marker Interface? It’s an interface with no methods or fields. It signals metadata to the JVM or compiler. Examples: Serializable (marks class for conversion to byte stream) and Cloneable (marks class as eligible for Object.clone()). ☑️3. How to Create an Immutable Class? Think of String or Wrapper classes. Follow these rules: • Declare the class final (or use private constructors). • Make all fields private and final. • No setter methods. • If holding a mutable object (like Date/Collection), return a defensive copy in the getter. ☑️4. Can Static Methods Be Overridden? No. Static methods are hidden, not overridden. Overriding relies on runtime object type (polymorphism), but static methods are resolved at compile-time based on the reference type. . . #Javadeveloper #springbootdeveloper #javadev #spring #coding #staticmethod
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