🚀 Day 41/100 of My LeetCode Challenge: Mastering Graph Traversal with Edge Reversal! 🎯 Today’s Problem: A clever graph traversal challenge where each node has a one-time switchthat can reverse an incoming edge—then traverse it immediately at double the cost. 🧠 Key Insights: Each node can use its switch at most once to reverse one incoming edge Reversed edges cost 2 × original weight Need to find the minimum cost path from node 0 to node n-1 🔧 My Approach: I modeled this as a Dijkstra's algorithm variant with an extra state dimension: dist[node][used] where used ∈ {0,1} tracks whether we've used the node's switch Maintain both outgoing edges (normal traversal) and incoming edges (if switch not used yet) Priority queue ensures we always expand the lowest-cost path first ⚡ Complexity: Time: O((V + E) log V) — Dijkstra's with modified state Space: O(V + E) — graph representation and distance matrix 📈 The Challenge: This problem beautifully combines: State-space search (tracking switch usage) Graph traversal optimization (Dijkstra's adaptation) Edge manipulation (dynamic reversal mechanics) 🔗 Why This Matters: Problems like these appear in: Network routing with one-time reconfiguration options Resource-constrained pathfinding Real-time strategy games with limited special moves Fault-tolerant network design #LeetCodeChallenge #100DaysOfCode #GraphTheory #Algorithms #DataStructures #ProblemSolving #Dijkstra #Java #CodingInterview #TechCommunity #SoftwareEngineering #Programming
Mastering Graph Traversal with Edge Reversal on LeetCode Challenge
More Relevant Posts
-
Day 56 of LeetCode Grind ⚡🔥 Problem: Minimum Cost Path with Edge Reversals (3650) Find the cheapest path in a directed graph where you can reverse incoming edges on the fly (at double the cost). 💡 Core Insight: * This is a classic Graph Modeling problem disguised as a new mechanic. * A normal edge u -> v with weight w exists as usual. * The ability to "reverse an incoming edge" essentially means there's also a path v -> u, but it costs 2 * w. * We don't need to track "switch usage" state because Dijkstra's algorithm naturally finds the optimal path. If it's cheaper to arrive at v and immediately flip an edge back to u, the algorithm treats it just like any other edge with weight 2w. Approach: * Build an adjacency list where: * Forward edges u -> v have weight w. * Backward edges v -> u have weight 2 * w. * Run standard Dijkstra's Algorithm from node 0. * The first time we pop node n-1, we have our answer. Complexity: * Time: O((N + E) log N) using a min-heap. * Space: O(N + E) to store the graph. ✨ Reflection: Sometimes "special moves" in graph problems are just standard edges with different weights. By modeling the "reverse switch" simply as a more expensive backward edge, we reduce a seemingly complex state-based problem into a standard shortest path search! #LeetCode #Day56 #GraphTheory #Dijkstra #Python #Algorithms #ProblemSolving #100DaysOfCode #Tech Day 56 in the books! 🚀 Ready for 57!
To view or add a comment, sign in
-
-
hi connections Today I tackled LeetCode 485: Max Consecutive Ones. It’s a classic "Easy" problem that perfectly illustrates a fundamental concept in algorithm design: State Management. The Problem: Given a binary array, find the maximum number of consecutive 1s. The Approach: Instead of nested loops or complex data structures, this is best solved with a simple Linear Scan. Maintain a current_streak counter. Iterate through the array once—O(n) time complexity. Update a max_streak variable whenever the current streak surpasses it. Reset the counter when you hit a 0. The Engineering Takeaway: This problem is a reminder that efficiency often comes from minimizing passes. Why sort or store data when you can solve the problem in a single, elegant sweep? It’s about keeping the "state" of your application lean and only tracking what is absolutely necessary. Whether you're processing a stream of binary data or managing user session streaks in a real-world app, the logic remains the same: Stay focused on the current window, but never lose sight of the record. #LeetCode #SoftwareEngineering #CleanCode #Algorithms #DataStructures #Python #CodingInterview #ProblemSolving
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
-
-
🚀 Just built my own Pathfinding Algorithm Visualizer from scratch! I’m excited to share my latest project: a real-time Pathfinding Algorithm Visualizer built with Python and JavaScript. Over the last few weeks, I’ve been on a "speedrun" of Data Structures & Algorithms for my academic exams. I wanted to go beyond just reading the theory—I wanted to truly understand and visualize how algorithms like Dijkstra, BFS, and DFS explore data. Instead of just memorizing them, I built a tool to watch them think. ✨ Key Features: Real-time Visualization: Watch algorithms traverse the grid node-by-node. Interactive Controls: Draw walls, move start/end nodes, and reset the grid instantly. Comparison: See the difference between the "concentric rings" of BFS versus the "winding snake" of DFS. 🛠️ Tech Stack & Architecture: I used the Eel framework to bridge a Python backend with a modern Vanilla JS frontend. What started as just another Python task turned into a full-stack challenge that I really enjoyed. You can see exactly how the system components talk to each other here: 👉 System Architecture Doc : https://lnkd.in/d_QRR5rC This project was a fantastic way to deepen my understanding of Graph Theory while implementing a clean, interactive architecture. Check out the full code on GitHub! 👇 [https://lnkd.in/dcSVaNA7] #Python #Algorithms #DataStructures #ComputerScience #WebDevelopment #Coding #Project #GraphTheory #DSA #BFS #DFS
To view or add a comment, sign in
-
-
🚀 LeetCode: Map Word Weights The goal is to calculate a transformation of words based on a given weight array and map the resulting total weight (modulo 26) to a character from a reversed alphabet. 🛠️ My Approach 1. Weight Calculation: I iterated through each word and calculated its total weight by mapping each character to its corresponding value in the weights array using charCodeAt(0) - 97. ⚖️ 2. Reversed Mapping: Instead of complex math to find the character, I used a pre-defined reversed_alpha string. By taking the totalWeight % 26, I could instantly grab the correct character. 🔡 3. Optimization: By using a nested loop structure and direct index access, I ensured the logic remains lean and lightning-fast. ⚡ 📊 Efficiency Analysis ⏱️ Time Complexity: O(N * M) where 'N' is the number of words and 'M' is the average length of each word. 💾 Space Complexity: O(1) (excluding the result string) as the alphabet mapping and variables use constant space. #LeetCode #JavaScript #CodingLife #Algorithms #WebDevelopment #ProblemSolving #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
Day 8 of Daily DSA 🚀 Solved LeetCode 319: Bulb Switcher 💡 Initially, the brute-force idea was to simulate all rounds using loops — but that leads to O(n) time complexity. 🔍 Key Insight (Math wins here): A bulb ends up ON only if it is toggled an odd number of times. This happens only for perfect squares, because only perfect squares have an odd number of divisors. So instead of looping till n, we can directly count perfect squares using: return (int) Math.sqrt(n); Why Math.sqrt() over loop? ✅ Reduces time complexity from O(n) → O(1) ✅ Cleaner & more readable code ✅ Much faster for large inputs Complexity: • Time: O(1) • Space: O(1) LeetCode Stats: • Runtime: 0 ms (Beats 100%) • Memory: 42.25 MB This problem is a great reminder that sometimes math is the real optimization 🧠✨ #DSA #LeetCode #Java #MathOptimization #ProblemSolving #DailyCoding #Consistency
To view or add a comment, sign in
-
-
I just recorded myself solving the Contains Duplicate problem and walking through a couple of different approaches. The problem: Given an integer array nums, return true if any value appears more than once. Otherwise, return false. Examples: • [1, 2, 3, 3] → true • [1, 2, 3, 4] → false 💡 Approach 1: Nested Loops (Brute Force) I started with a double loop to compare every pair of elements. ⏱ Time Complexity: O(n²) 📦 Space Complexity: O(1) It works, but it’s not scalable for large inputs. 💡 Approach 2: Sort + Single Pass (Optimized) Then I improved the solution by: 1️⃣ Sorting the array 2️⃣ Looping once to check adjacent elements If nums[i] === nums[i - 1], we’ve found a duplicate. ⏱ Time Complexity: O(n log n) (because of sorting) 📦 Space Complexity: Depends on the sorting implementation I enjoy breaking problems down this way — starting simple, then refining the solution step by step. That’s where real learning happens. Here’s the full walkthrough video: 🔗 https://lnkd.in/efeFYhtC #NeetCode #Algorithms #DataStructures #CodingInterview #JavaScript #SoftwareEngineering #ProblemSolving
To view or add a comment, sign in
-
hi connections I just tackled LeetCode #2976, a problem that perfectly illustrates why we use specialized graph algorithms for optimization. The Challenge: Convert a source string to a target string with minimum cost, given a list of character-to-character conversion rules. The Strategy: Since any character can potentially transform into another through a chain of intermediate steps (e.g., a \to b \to c), this is a Shortest Path problem. Because we need to know the cost between any two characters, I implemented the Floyd-Warshall Algorithm. The Logic: Initialize: Create a 26 \times 26 matrix with infinity, and 0 on the diagonal. Fill: Add the direct costs from the input. Optimize: Iterate through every possible intermediate character k to see if i \to k \to j is cheaper than the current i \to j. By pre-computing this matrix, the final string conversion becomes a simple O(n) lookup. #GraphTheory #Algorithms #FloydWarshall #LeetCode #SoftwareEngineering
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟰𝟯/𝟭𝟬𝟬 | 𝗠𝗲𝗿𝗴𝗲 𝗡𝗼𝗱𝗲𝘀 𝗶𝗻 𝗕𝗲𝘁𝘄𝗲𝗲𝗻 𝗭𝗲𝗿𝗼𝘀 Day 43 ✅ — In-place transformation. 𝗧𝗼𝗱𝗮𝘆'𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: ✅ 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 #𝟮𝟭𝟴𝟭: Merge Nodes in Between Zeros (Medium) 𝗪𝗵𝗮𝘁 𝗖𝗹𝗶𝗰𝗸𝗲𝗱: Sum all values between consecutive zeros, replace the first zero with the sum, remove intermediate nodes. The challenge? Do it in-place without creating a new list. Reuse existing nodes to save space. Fourteen days of linked list practice paid off—modifying the list structure while traversing feels natural now. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: 👉 Track prev (result node) and temp (current node) 👉 Sum values between zeros 👉 When hitting zero, update prev.val with sum 👉 Adjust pointers to skip merged nodes Time: O(n), Space: O(1) 𝗠𝘆 𝗥𝗲𝗮𝗹𝗶𝘇𝗮𝘁𝗶𝗼𝗻: Fourteen linked list problems. In-place modifications used to seem tricky. Now they're just careful pointer work. Progress isn't always visible day-to-day. But Day 43 compared to Day 30? Night and day. 𝗖𝗼𝗱𝗲:🔗 https://lnkd.in/gxmPNksx 𝗗𝗮𝘆 𝟰𝟯/𝟭𝟬𝟬 ✅ | 𝟱𝟳 𝗺𝗼𝗿𝗲 𝘁𝗼 𝗴𝗼! #100DaysOfCode #LeetCode #LinkedList #InPlaceAlgorithm #DataStructures #CodingInterview #SoftwareEngineer #Java #Algorithms #MediumLevel #Programming #SpaceOptimization
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