🚀 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
LeetCode DFS Challenge: Grid Movement with Directional Checks
More Relevant Posts
-
🚀 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
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/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/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
-
-
🚀 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
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gdjyFXCw First, we note that swaps aren't random; they are only allowed between specific index pairs. If index `a` can swap with `b`, and `b` can swap with `c`, then `a`, `b`, and `c` become connected. We can rearrange values freely among them. This means we need to identify groups of indices where swapping is allowed within the group. To find these groups efficiently, we use Disjoint Set Union (DSU). Each index starts in its own set. For every allowed swap pair `[x, y]`, we combine their sets. After processing all the swaps, indices that share the same parent belong to the same connected component or group. Next, we organize all indices by their DSU parent. Each group shows a set of positions where we can rearrange values without restrictions. For each group, we aim to match values from `source` to `target` as closely as possible: * First, we count how often each value appears in `source` for that group. * Then, we go through the same indices in `target`. For each value: * If the value exists in our frequency map (meaning we have it in `source`), we use it and decrease its count. * If it doesn't exist, it means we can't match this value in the group, contributing to the Hamming distance. By doing this for all groups, we maximize matches within each connected component, which minimizes the overall Hamming distance. 👉 My Solution: https://lnkd.in/gfx3iMut 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/gdWsKciF This solution finds the maximum distance between two houses of different colors based on a key observation: the maximum distance will always involve either the first house or the last house. Instead of checking all possible pairs, which would take O(n²), the code improves the method by making a single pass through the array. It starts with an answer of 0 and goes through each index `i`. For each house, it does two checks. First, it compares the current color with the color of the first house (index 0). If they are different, the distance between them is simply `i`, and we update the maximum distance. This identifies the farthest house from the start that has a different color. Next, it compares the current color with the color of the last house (index n-1). If they are different, the distance is `(n - 1 - i)`, and we update the maximum if necessary. This identifies the farthest house from the end that has a different color. By doing this, the algorithm effectively captures the maximum possible distance without checking every pair. Since it requires only one loop through the array, the time complexity is O(n) and the space complexity is O(1). 👉 My Solution: https://lnkd.in/gg_5J_DF 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
-
-
I just returned false on a LeetCode problem… and it passed ALL 67 test cases. No loops. No base conversions. No palindrome checks. Just one line: return false; And it got accepted instantly. The problem? 2396. Strictly Palindromic Number You had to check if a number n is a palindrome in every base from 2 to n-2. Sounds brutal, right? Then I actually read the problem properly. Here's the mind-blowing part: For any n ≥ 4, when you convert it to base (n-2), it always becomes "12". n=5 → base 3 → "12" n=6 → base 4 → "12" n=10 → base 8 → "12" "12" is never a palindrome. So it's mathematically impossible for any number ≥ 4 to be strictly palindromic. For n=1,2,3 the base range is invalid anyway. The answer is always false. The entire "hard" problem collapses into a single line of code. Lesson for every developer: Before you write clever code, ask yourself: Is this problem even possible? Sometimes the best solution isn’t optimized algorithms. It’s pure elimination. O(1) thinking. Read the problem. Really read it. #LeetCode #ProblemSolving #SoftwareEngineering #Coding #DSA #BackendEngineering #CodingInterview #DeveloperMindset #CleanCode
To view or add a comment, sign in
-
-
Ever look at a LeetCode problem and think, "Oh, this is just simple math," only to see a constraint of $10^{15}$ staring back at you? That was my experience with the "Count Good Numbers" problem today. The core logic was actually pretty straightforward: even indices get even digits (5 options), and odd indices get prime digits (4 options). But trying to calculate 5^even * 4^odd for massive numbers? Immediate Time Limit Exceeded (TLE). I had to scrap the standard approach and write a custom pow() function using Binary Exponentiation. It’s wild how applying modulo 10^9 + 7 at every single multiplication step within the recursive call is the exact difference between a failing solution and a clean O(log n) pass without integer overflow. Definitely a great reminder that knowing the brute-force math is only half the battle—optimizing it is where the real engineering happens. Back to the grind! #LeetCode #DSA #CPP #CompetitiveProgramming #SoftwareEngineering #CodingJourney
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/g8Xgd5wx The function goes through each word in the `queries` array. For every query word, it compares it with each word in the `dictionary`. Since all words are assumed to have the same length, it performs a character-by-character comparison. For each pair of words, a counter called `unequal` tracks how many positions have different characters. The code loops through each index of the word and increases this counter whenever the characters at the same position do not match. If the number of differing characters is 2 or less at any point, it means the query word can change into that dictionary word with at most two edits. In this case, the query word is added to the result list, and the inner loop stops early, using `break` to avoid unnecessary comparisons with other dictionary words. Finally, after checking all query words, the function returns the list of valid words that meet the condition. 👉 My Solution: https://lnkd.in/gMnYvSvx 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
-
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