Day 102 of 365 Days of code I'm falling in love with graphs 🕷️ Ever wondered how multi source bfs works "_". i thought we must be using some kind of concurrency or threading concepts to do perform bfs parallely at the same time. Then i saw some discussion from CF, and a guy said consider bfs search has multiple sources, each starting from a part of graph. A simple solution is to think about an imaginary node connecting all these multiple sources, and push the imaginary node into queue. Thereby you will be able simultaneously traverse the graph, where it looks like each of the node will be performed a bfs search, simultaneously. Instead of using an imaginary node, just push all the source nodes into the queue. and start performing bfs. both of the approaches are the same, we reach the second state after performing the first one, so instead of wasting time on constructing an imaginary node we directly enqueue the source nodes into the queue. SOrry for the bad english, i'm feeling sleepy :( Qn 1) Rotten oranges Approach: Multi Source Bfs Explanation: i wanna sleep bruv #365daysOfCode #NeetCode #leetcode #DSA #python #LeetCode #ProblemSolving #Algorithms #365dayschallenge
Multi Source BFS Explained with Python Example
More Relevant Posts
-
𝗗𝗮𝘆 𝟲𝟴/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 136. Single Number 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Easy 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: Given a non-empty array where every element appears twice except for one, find the element that appears only once. Constraints: • Linear time complexity required • Constant extra space 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: This problem is efficiently solved using Bit Manipulation (XOR operation). • Key Properties of XOR: – a ^ a = 0 – a ^ 0 = a – XOR is commutative and associative • Logic: – XOR all elements in the array – Duplicate numbers cancel each other out – The remaining value is the unique element • Implementation: – Initialize a variable (e.g., result = 0) – Traverse the array and XOR each element with result – Final result holds the single number This works because pairs eliminate themselves, leaving only the non-repeating number. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(n) • Space Complexity: O(1) 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Bit manipulation can simplify problems that seem to require extra space. XOR is especially powerful when dealing with pairs or duplicates. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/guP-fJnC #Day68of75 #LeetCode75 #DSA #Java #Python #BitManipulation #Algorithms #MachineLearning #DataScience #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
To view or add a comment, sign in
-
-
Day 105: Circular Arrays & Shortest Paths 🔄 Problem 2515: Shortest Distance to Target String in a Circular Array Today’s challenge involved finding the minimum steps to reach a target string in a circular array, allowing movement in both directions. The Strategy: • Bidirectional Search: Since the array is circular, the distance can be calculated in two ways: moving forward or moving backward. • Modular Arithmetic: I used (dist + n) % n to handle the wrap-around logic seamlessly, ensuring the index stays within bounds regardless of the direction. • Optimization: By iterating once through the array and comparing the distances for every occurrence of the target, I maintained an O(N) time complexity. Sometimes the most elegant way to handle a "circular" problem is simply embracing the symmetry of the path. 🚀 #LeetCode #Java #Algorithms #ProblemSolving #DailyCode
To view or add a comment, sign in
-
-
🚀 Day 574 of #750DaysOfCode 🚀 🔍 Problem Solved: Detect Cycles in 2D Grid Today’s problem was a great example of how graph concepts show up in grids 👀 💡 Key Insight: A grid can be treated as a graph where: Each cell = node Adjacent same-value cells = edges 👉 The task is to detect a cycle of same characters with length ≥ 4 🧠 Approach (DFS + Parent Tracking): Traverse each cell Start DFS if not visited While exploring: Move only to same character cells Track previous (parent) cell If we visit an already visited cell (not parent) → ✅ cycle found 📈 Complexity: Time: O(m × n) Space: O(m × n) ✨ Takeaway: 👉 Many grid problems are just graph problems in disguise 👉 Cycle detection becomes easy with DFS + parent tracking Another solid concept added to the toolkit 💪 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Graphs #DFS #Algorithms #LearningEveryday
To view or add a comment, sign in
-
-
💡 Day 64 of LeetCode Problem Solved! 🔧 🌟 2033. Minimum Operations to Make a Uni-Value Grid 🌟 🔗 Solution Code: https://lnkd.in/gts2KBqr 🧠 Approach: • Flattened the 2D grid into a sorted 1D list. • Chose the median as the target value — it minimises total absolute deviation mathematically. • Early-exit with -1 if any element has a different remainder mod x than the median. • Summed |element - median| / x for all elements to get the answer. ⚡ Key Learning: • The median is the optimal target for minimising sum of absolute differences — a powerful mathematical insight that replaces brute-force enumeration entirely. • A simple remainder check handles all impossible cases upfront. ⏱️ Complexity: • Time: O(m·n·log(m·n)) • Space: O(m·n) #LeetCode #Java #DSA #ProblemSolving #Consistency #CodingJourney #Algorithms #Grid
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 74 of #100DaysOfCode 🧩 LeetCode 220 – Contains Duplicate III (Hard) Today’s problem was a solid mix of logic + optimization. Not brute-force friendly at all — you have to think smart. 🔍 Problem Statement: Given an array "nums" and two integers "indexDiff" and "valueDiff", check if there exist two indices "i" and "j" such that: ✔️ "i ≠ j" ✔️ "|i - j| ≤ indexDiff" ✔️ "|nums[i] - nums[j]| ≤ valueDiff" 💡 Approach Used (Bucket + Sliding Window): Instead of comparing every pair (which would be too slow), I used: 👉 Bucketization Technique 👉 Sliding Window Constraint Each number is placed into a bucket of size "valueDiff + 1". - Same bucket ⇒ valid pair - Neighbor buckets ⇒ check manually - Maintain only last "indexDiff" elements ⚡ Why this works: It reduces time complexity from O(n²) → O(n) 📊 My Performance: ⏱️ Runtime: 139 ms 💾 Memory: 37.38 MB 🔥 Key Learning: Efficient problems are less about coding and more about choosing the right data structure. #Day74 #LeetCode #100DaysOfCode #DSA #CodingJourney #Python #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
Day 45 of Daily DSA 🚀 Solved LeetCode 867: Transpose Matrix ✅ Problem: Given a 2D matrix, return its transpose (rows become columns and columns become rows). Approach: Created a new matrix and swapped indices while traversing. Steps: Get number of rows and columns Create a new matrix of size cols x rows Traverse original matrix Assign: trans[j][i] = matrix[i][j] Return the new matrix ⏱ Complexity: • Time: O(n × m) • Space: O(n × m) 📊 LeetCode Stats: • Runtime: 0 ms (Beats 100%) ⚡ • Memory: 46.46 MB Simple transformations like transpose build strong fundamentals for matrix-based problems 💡 #DSA #LeetCode #Java #Arrays #Matrix #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day 55/75 — Shortest Subarray with Sum at Least K Today’s problem was a challenging one involving prefix sums and a monotonic deque. Approach: • Use prefix sum to convert subarray sum into difference of indices • Maintain a deque to keep indices in increasing order of prefix sums • Remove useless indices to keep it optimal Key logic: while (!dq.isEmpty() && ps[j] - ps[dq.peekFirst()] >= k) { minLen = Math.min(minLen, j - dq.pollFirst()); } while (!dq.isEmpty() && ps[j] <= ps[dq.peekLast()]) { dq.pollLast(); } dq.offerLast(j); Time Complexity: O(n) Space Complexity: O(n) A tough problem that builds strong intuition for prefix sums + deque optimization. 55/75 🚀 #Day55 #DSA #PrefixSum #Deque #Java #Algorithms #LeetCode
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
More from this author
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