✳️Day 35 of #100DaysOfCode✳️ 📌 Cracking the "Redundant Connection" Problem with DSU! 🛠️ My Approach: The DSU Strategy The Disjoint Set Union (or Union-Find) algorithm is perfect here because it allows us to track connected components efficiently as we iterate through the edges. ✨The Steps in my Code: 1️⃣Initialization: Created a parent array where every node is initially its own parent (representing n independent sets). 2️⃣Iterative Union: For every edge (u, v) in the input: Find the root (representative) of u. Find the root (representative) of v. Cycle Detection: * If find(u) == find(v), it means u and v are already part of the same connected component. Adding this edge would create a cycle. 🚩 Since the problem asks for the last edge that causes the cycle, I return this edge immediately. 3️⃣Union: If they are in different sets, I perform a union by setting the parent of one root to the other. 4️⃣Optimization: I used Path Compression in the find function to keep the tree flat, ensuring almost constant time complexity. 💡 When should you use DSU? 🔅DSU is a powerhouse for specific graph scenarios. Reach for it when: Cycle Detection: You need to check if adding an edge creates a cycle in an undirected graph. 🔅Connected Components: You need to count or manage groups of connected nodes dynamically. 🔅Minimum Spanning Trees: It’s the backbone of Kruskal’s Algorithm. Grid Problems: Identifying "islands" or connected regions in a 2D matrix. #DataStructures #Algorithms #LeetCode #Java #GraphTheory #CodingLife #SoftwareEngineering
Cracking the Redundant Connection with DSU Algorithm
More Relevant Posts
-
Day 94: Slanted Ciphertext & Loop Optimization 📟 Problem 2075: Decode the Slanted Ciphertext Today’s solve was a fun callback to the "ZigZag Conversion" problem I've tackled before. The challenge: read a string that was written diagonally across a matrix and then flattened into a single row. The Strategy: • Diagonal Traversal: The key is calculating the step size. In a slanted cipher, the next character in a diagonal is exactly columns + 1 indices away. • Refining the Loop: My first approach worked well, but I realized I could shave off execution time by adding an early exit. • The "Efficiency" Jump: By adding a simple check, if(j % column == column-1) break;—I stopped the inner loop from looking for diagonal neighbors that would logically fall outside the matrix boundaries. The Result: This small logic tweak dropped my runtime from 28ms down to 18ms, jumping from beating 56% to 97.63% of users. It’s a great reminder that even on "easier" problems, there’s always room to optimize. Seeing that performance graph move to the far left is the best kind of motivation. 🚀 #LeetCode #Java #StringManipulation #Algorithm #Optimization #DailyCode
To view or add a comment, sign in
-
-
🚀 Day 82 — Kadane’s Algorithm (Maximum Subarray Sum with One Deletion) Pushing forward with a more advanced Kadane variation — today I solved a problem where you’re allowed to delete at most one element from the subarray to maximize the sum. 📌 Problem Solved: LeetCode 1186 – Maximum Subarray Sum with One Deletion 🧠 The Twist on Standard Kadane: We now need to track two states at each index: nd = maximum subarray sum ending at i with no deletion used so far. od = maximum subarray sum ending at i with exactly one deletion used so far. Transition logic: nd = Math.max(arr[i], nd + arr[i]) → classic Kadane (no deletion). od = Math.max(nd_prev, od_prev + arr[i]) → either skip deleting this element (so use previous no‑deletion state) or extend a previously deleted subarray. Why track both? Because at any point, the best subarray ending here may have never deleted, or may have deleted a previous element. The answer is the max of all nd and od across the array. 💡 Key Insight: Kadane’s pattern isn’t just one variable — it scales to multiple states. This “state‑based DP” approach is the bridge between Kadane and more complex subarray problems. No guilt about past breaks — just leveling up one variation at a time. #DSA #KadaneAlgorithm #MaximumSubarrayWithDeletion #LeetCode1186 #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
Day 99: Square Root Decomposition & Prefix Multiplications ⚡ Problem 3655: XOR After Range Multiplication Queries II Yesterday’s brute force approach hit a wall today with a TLE (Time Limit Exceeded). The constraints were significantly tighter, requiring a more sophisticated optimization. The Strategy: Square Root Decomposition To handle the queries efficiently, I split the problem based on the step size k: • Large Steps (k ≥ √N): For large gaps, the number of updates is small enough that direct simulation still works within time limits. • Small Steps (k < √N): This is where the magic happens. For small k, I used a Difference Array technique modified for multiplications. • Modular Inverse & Prefix Products: Instead of updating every index, I marked the start (L) and end (R) of the range. I used modInverse to "cancel out" the multiplication after the range ended. A final prefix product pass (jumping by k) applied all updates in O(N) time. Technical Highlights: • Fermat's Little Theorem: Used modPow(x, MOD - 2) to calculate the modular inverse for division. • Complexity: Reduced the worst-case runtime from O(Q⋅N) to O((Q+N)√N). One day away from 100, but the focus remains on the problem in front of me. Consistency isn't about the destination; it's about the quality of the journey. 🚀 #LeetCode #Java #Algorithms #DataStructures #SquareRootDecomposition #DailyCode
To view or add a comment, sign in
-
-
Day 115 - LeetCode Journey Solved LeetCode 236 – Lowest Common Ancestor of a Binary Tree ✅ This problem revolves around identifying the lowest common ancestor (LCA) of two given nodes in a binary tree. The LCA is defined as the lowest node in the tree that has both nodes as descendants (a node can be a descendant of itself). Approach: I used a recursive depth-first search (DFS) approach to efficiently locate the LCA. The idea is simple but powerful: • If the current node is null, return null • If the current node matches either of the target nodes (p or q), return the node • Recursively search in the left and right subtrees After recursion: • If both left and right calls return non-null values, the current node is the LCA • If only one side returns non-null, propagate that result upward This works because the first node where both targets split into different subtrees becomes the lowest common ancestor. Complexity Analysis: • Time Complexity: O(n), as we traverse each node once • Space Complexity: O(h), where h is the height of the tree (recursion stack) Key Takeaways: • Tree problems often rely on recursive decomposition 🌳 • Returning meaningful values from recursion simplifies logic • LCA is a classic concept frequently asked in interviews All test cases passed successfully 🎯 #LeetCode #DSA #BinaryTree #Recursion #Java #CodingJourney #InterviewPrep
To view or add a comment, sign in
-
-
🚀 Day 8/100 — #100DaysOfLeetCode Another day, another concept unlocked 💻🔥 ✅ Problem Solved: 🔹 LeetCode 73 — Set Matrix Zeroes 💡 Problem Idea: If any element in a matrix is 0, its entire row and column must be converted to 0 — and the challenge is to do this in-place without using extra space. 🧠 Algorithm & Tricks Learned: Instead of using extra arrays, we can use the first row and first column as markers. First pass → mark rows and columns that should become zero. Second pass → update the matrix based on those markers. Carefully handle the first row and first column separately to avoid losing information. ⚡ Key Insight: The matrix itself can act as storage, reducing extra memory usage. 📊 Complexity Analysis: Time Complexity: O(m × n) → traverse matrix twice Space Complexity: O(1) → solved in-place without extra data structures This problem taught me how small optimizations can significantly improve space efficiency. Learning to think beyond brute force every day 🚀 #100DaysOfLeetCode #LeetCode #DSA #MatrixProblems #Algorithms #Java #ProblemSolving #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
-
Day 71/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Maximum Subarray Min-Product A powerful problem combining prefix sums and monotonic stack. Problem idea: For every subarray, calculate (minimum element × sum of subarray) and find the maximum value. Key idea: Monotonic stack + prefix sum optimization. Why? • Brute force would be too slow (O(n²)) • Need to efficiently find range where each element is minimum • Prefix sum helps compute subarray sum in O(1) How it works: • Build prefix sum array • Use monotonic increasing stack • For each element, find its left & right boundary • Treat each element as the minimum of a subarray • Compute subarray sum using prefix • Multiply with element → track maximum Time Complexity: O(n) Space Complexity: O(n) Big takeaway: Monotonic stack helps solve “nearest smaller element” problems efficiently, which unlocks many advanced patterns. 🔥 Day 71 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #MonotonicStack #PrefixSum #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
📅 Date: April 25, 2026 Day 4 of my LeetCode Journey 🚀 ✅ Problem Solved: 9. Palindrome Number 🧠 Approach & Smart Solution: While it's easy to solve this by converting the integer to a string and reversing it, that takes extra memory! I opted for a highly optimized mathematical approach. I reversed the integer by peeling off its digits one by one using modulo and division, keeping the space complexity to an absolute minimum. • Pseudo-code: Handle edge cases: If the number is less than 0, it can't be a palindrome, so return false. Store the original number in a temporary variable for final comparison. Initialize a 'reverse' variable to 0. Loop while the number is greater than 0: Extract the last digit: digit = x % 10. Add it to the reversed number: reverse = (reverse * 10) + digit. Remove the last digit from the original number: x = x / 10. Finally, return true if the original number matches the reversed number. This math-based solution avoids expensive string conversions and runs instantly! ⏱️ Time Complexity: O(log₁₀(n)) (We only iterate through the digits of the number) 📦 Space Complexity: O(1) (Only using a few integer variables) 📊 Progress Update: • Streak: 3 Days 🔥 • Difficulty: Easy • Pattern: Math / Digit Extraction 🔗 LeetCode Profile: https://lnkd.in/gBcDQwtb (@Hari312004) Choosing mathematical operations over string manipulations is a great way to optimize basic algorithms! 💡 #LeetCode #DSA #Math #Java #CodingJourney #ProblemSolving #InterviewPrep #Consistency #BackendDevelopment
To view or add a comment, sign in
-
-
#70DayStreak 🚀 27/04/26 — Optimized Sliding Window | Longest Substring Without Repeating Characters (LeetCode 3) Today I revisited a classic problem — Longest Substring Without Repeating Characters — and implemented a more optimized Sliding Window using HashMap. Previously, I used a HashSet approach where the window shrinks step-by-step. This time, I upgraded it with a "jumping window" technique, allowing direct pointer movement. 🔑 Key Optimization Insight Instead of removing characters one by one: • Store last seen index of each character • When duplicate appears → jump left pointer instantly • Avoid unnecessary iterations 👉 This reduces redundant work and improves efficiency significantly. ⚙️ Algorithm Highlights • Left pointer jumps using stored indices • Right pointer scans once • Continuous max window calculation 📊 Complexity • Time: O(n) • Space: O(min(m, n)) 📈 Performance • Runtime: 5ms (Beats 87.15%) • Memory: 45.67 MB (Beats 69.72%) 🔥 Consistency Metrics • 84 Active Days • 70-Day Streak 💡 Key Learning Switching from HashSet → HashMap transforms the approach from iterative shrinking to direct optimization. This is a small shift in thinking, but a big upgrade in performance. 📌 Even after 100+ problems, refinement and optimization still matter. #DSA #Java #LeetCode #SlidingWindow #HashMap #Algorithms #CodingJourney #ProblemSolving #Optimization #100DaysOfCode
To view or add a comment, sign in
-
-
Day 79/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Flatten Binary Tree to Linked List A powerful tree transformation problem using pointer manipulation. Problem idea: Convert a binary tree into a linked list in-place following preorder traversal. Key idea: Iterative traversal + rewiring (similar to Morris traversal idea). Why? • We need preorder sequence (Root → Left → Right) • Instead of extra space, we modify pointers in-place • Efficient and avoids recursion stack How it works: • Traverse using a pointer curr • If left child exists: → Find rightmost node of left subtree → Connect it to current’s right subtree → Move left subtree to right → Set left = null • Move to next node (curr.right) Time Complexity: O(n) Space Complexity: O(1) Big takeaway: Tree problems can often be optimized using in-place pointer rewiring, avoiding extra space. 🔥 This pattern is very useful for tree flattening and traversal optimizations. Day 79 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #BinaryTree #MorrisTraversal #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
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