🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gxcUfyyz The first logic that came to my mind after seeing the question was — this is a cycle detection problem. Since the path isn't fixed, it's an undirected cycle detection problem. Just applied that and voila — solved! The constraints and multiple possible paths gave a clear hint towards DFS. The grid is just an undirected graph — each cell is a node, and two adjacent cells are connected only if they share the same character. So the problem reduces to: does any connected component of same-character cells contain a cycle? Run DFS from every unvisited cell, tracking the parent to avoid treating the edge we came from as a back edge. If we hit an already-visited cell that isn't our direct parent — cycle found. ⏱️ Time: O(m × n) | Space: O(m × n) 👉 My Solution: https://lnkd.in/gATmwcnU If you found this helpful, feel free to ⭐ the repo or connect! 🙂 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
LeetCode Daily Challenge: Cycle Detection in Grid
More Relevant Posts
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/eGmHt3nW The grid consists of six street types, and each allows movement in exactly two directions. These types are outlined in a map at the start: - Type 1: left/right - Type 2: up/down - Type 3: down/left - Type 4: down/right - Type 5: left/up - Type 6: right/up The depth-first search (DFS) begins at the point (0,0) with a marker `{-2,-2}`, indicating "no incoming direction yet." Before moving on from any cell, two checks are necessary: When reaching a cell using the direction `{dir1, dir2}`, the current street must include `{-dir1, -dir2}` in its connection list. This represents the exact opposite direction and confirms the street physically connects back to where you came from. If neither of the two connections matches, the path is deemed invalid, and the process returns false right away. As streets make up a fixed graph with possible cycles, the `visited` marker identifies cells that have already been seen before checking neighboring cells. Any neighbor that is already marked is skipped. Without this, the DFS would loop through a cycle endlessly. The check for the incoming direction alone cannot prevent this, as it only reveals the immediate previous direction, not the entire path taken. Once both checks are satisfied, the cell is marked as visited, and DFS explores unvisited neighbors. Each street has precisely two connections, leading to a maximum of two neighbors to consider. In practice, one neighbor is usually blocked by the `visited` marker (the cell you just came from), so most steps tend to be linear rather than branching. 👉 My Solution: https://lnkd.in/e8-6pePg If you found this helpful, feel free to ⭐ the repo or connect! 🙂 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/g9SGp2Qa 💡 My thought process: First, create a mapping from each value to a sorted list of its indices using a map<int, vector<int>>. This allows for easy lookup of all positions where a value occurs. For each query index idx, it retrieves the corresponding value num. If that value appears only once, the result is -1 because no valid pair exists. In case of multiple occurrences, we use binary search on the index list of num: * upper_bound finds the next occurrence that is strictly greater than idx. * lower_bound locates the current position and checks the previous occurrence. It calculates distances in both directions: * Forward distance: either direct (next - idx) or circular wrap (n - (idx - first)). * Backward distance: either direct (idx - prev) or circular wrap (n - (last - idx)). The minimum of these distances is stored as the answer. 👉 My Solution: https://lnkd.in/gjmKVa3y 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/gqTik3da 💡 My thought process: First, save all indices of each number in a map. The key is the number, and the value is a sorted list of its positions in the array. Then, for every index i, it computes the reverse of nums[i]. While reversing, it skips leading zeros. This means that a number like 120 becomes 21 instead of 021. After getting the reversed number, check the map for all indices where this reversed value exists. Using upper_bound, find the first index that is strictly greater than i. If such an index exists, calculate the distance between the two indices and update the minimum distance. Finally, if no such pair is found, it returns -1. Otherwise, it returns the minimum distance found. 👉 My Solution: https://lnkd.in/gpNu3WGh 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 40 | 100 Days of Coding Challenge #DrGViswanathanChallenge 📘 Problem Solved: Sum of Subarray Ranges (LeetCode) 🔧 Approach Used (Brute Force): • Considered every possible subarray • Maintained current minimum and maximum while expanding subarray • Calculated range = max - min for each subarray • Added all ranges to get final answer 📌 Key Idea: For each subarray, track the largest and smallest element, and compute their difference. ⏳ Complexity: Time: O(n²) Space: O(1) 🧠 Key Learning: Even though brute force works, it helps in understanding the pattern before optimizing. 💡 Optimization Insight: This problem can be optimized using monotonic stacks by calculating contribution of each element as min and max separately. 📂 Topics Covered: Arrays, Brute Force 📊 Example: Input: [1,2,3] Output: 4 🔥 Step by step moving from brute force → optimal solutions 🚀 #100DaysOfCode #DSA #CPP #LeetCode #CodingJourney #CompetitiveProgramming
To view or add a comment, sign in
-
-
Day 29 – LeetCode Journey 🚀 Solved Two Sum II – Input Array Is Sorted using the Two Pointer technique, leveraging the sorted nature of the array for an optimal solution. 🔹 Time Complexity: O(n) 🔹 Runtime: 2 ms (Beats 96.37%) 🔹 Memory Usage: 48.58 MB This problem is a great reminder that recognizing patterns (like sorted arrays) can significantly reduce complexity and improve efficiency. Small optimizations, big impact 📈 Staying consistent and sharpening problem-solving skills every day. #LeetCode #DSA #ProblemSolving #CodingJourney #SoftwareEngineering #Consistency #Learning
To view or add a comment, sign in
-
-
DAY->26 🚀 LeetCode 1002 — Find Common Characters | Frequency Optimization 🔥 Solved this problem using a frequency array approach and achieved 100% runtime (0 ms) ⚡ 🔍 The goal is to find characters that appear in all strings, including duplicates. 💡 Approach: Use a frequency array of size 26 Initialize with a large value (INT_MAX) For each word: Count character frequency Update global frequency using minimum values 🧠 Key Insight: We take the minimum frequency because a character must exist in every string. ⚡ Complexity: Time → O(n × k) Space → O(1) This problem helped me understand how frequency comparison can efficiently find common elements 🚀 #DSA #LeetCode #Cpp #Coding #ProblemSolving #Arrays #LearningJourney
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gZ52pSZR 💡 My thought process: The solution operates in two separate passes: 1. Left-to-Right Pass: For each element at index "i", calculate the distance to all previous occurrences of that value. If a value has appeared "k" times before, the sum of distances is found using this formula: (count * current_index) - (sum of previous_indices). By storing the count and the running sum of indices in a hash map, we can compute this in constant time. 2. Right-to-Left Pass: The same logic is applied in reverse to calculate the distance from the current index to all future occurrences. In this case, the formula changes to: (sum of future_indices) - (count * current_index). By adding the results from both directions, the code captures the total absolute difference for every identical pair without the performance cost of a nested loop. 👉 My Solution: https://lnkd.in/gfEc7Kis If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/giAcdv2U 💡 My thought process: This solution uses 3D dynamic programming to find the maximum coins that can be collected from the top-left to the bottom-right of a grid, allowing up to 2 neutralizations for negative cells. The state dp[i][j][k] stores the maximum coins reachable at cell (i, j) using k neutralizations. For each cell, transitions are taken from the left and top cells. If the current cell is negative, two options are considered: either neutralize it (if k > 0) and carry forward the previous value without adding the negative, or do not neutralize and add the cell value. For non-negative cells, the value is simply added to the best of the previous states. The starting cell is initialized separately based on whether it is neutralized or not. The final answer is the maximum value among dp[m-1][n-1][0], dp[m-1][n-1][1], and dp[m-1][n-1][2]. 👉 My Solution: https://lnkd.in/gZWS3Kns 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 27 – LeetCode 💻 Solved: Remove Outermost Parentheses (Easy) Approach: Stack Depth / Counter Technique Used a counter to track the depth of parentheses ➡️ Increment on ‘(’ and decrement on ‘)’ ➡️ Add character only when it is not part of outermost layer This helps in removing the outermost parentheses of each primitive string efficiently 🚀 Time Complexity: O(n) Space Complexity: O(n) 💡 Concepts Used: Strings + Stack Logic (without extra stack) + Greedy #ApnaCollege #ShradhaKhapra #AmanDhattarwal #LeetCode #Day27 #DSA #Coding #Consistency #KeepGrinding 💪
To view or add a comment, sign in
-
-
🚀 LeetCode 378 — Kth Smallest Element in a Sorted Matrix | Solved ✅ Solved this interesting problem using Binary Search on Answer — a powerful pattern! 🔍 Problem Insight: Matrix is sorted row-wise and column-wise, but not flattened. 💡 Approach: • Applied binary search on value range • For each mid, counted elements ≤ mid using matrix properties ⚡ Time Complexity: O(n × log(max - min)) ✨ Key Learning: Not all binary search problems are about indices — sometimes we search in the answer space. 📈 Result: Accepted ✔️ From searching positions → to searching values That’s where problem-solving evolves 🔥 Grateful to Pratyush Narain for the guidance and clear explanations. #LeetCode #DSA #BinarySearch #ProblemSolving #CodingJourney
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