Recently solved "LeetCode 1970 – Last Day Where You Can Still Cross" and learned an interesting optimization. My first approach used DFS + binary search, which worked but wasn’t very efficient. Instead, I tried a reverse incremental BFS: - Start with all cells flooded - Unflood cells one by one in reverse order - Incrementally propagate reachability from the top row Each cell is processed at most once, giving amortized O(R×C) runtime — similar to Union-Find, but using BFS. Even if you’re not familiar with DSU, this method is intuitive: just track which cells are reachable from the top as you unflood the grid. While most online solutions use Union-Find or binary search + BFS/DFS, this incremental BFS approach is less commonly discussed and performs extremely well (~8× faster than DFS + binary search in Python). Sharing the solution here: 🔗 [https://lnkd.in/gVkzaSgj] #algorithms #problemSolving #softwareengineering
Optimized LeetCode 1970 Solution with Incremental BFS
More Relevant Posts
-
𝗗𝗮𝘆 𝟳: 𝗟𝗼𝗼𝗽𝘀 𝗶𝗻 𝗣𝘆𝘁𝗵𝗼𝗻 🐍 Loops are used to repeat a block of code until a condition is met. 𝗧𝘆𝗽𝗲𝘀 𝗼𝗳 𝗹𝗼𝗼𝗽𝘀 𝗶𝗻 𝗣𝘆𝘁𝗵𝗼𝗻: 1️⃣ for loop 🔹Used to iterate over a sequence (list, tuple, string, range, etc.) and executes the code once for each value in the sequence. 🔹Syntax: for item in sequence: # code block 2️⃣ while loop 🔹Runs as long as the condition remains True. 🔹Syntax: while condition: # code block ✍️Important Notes: ✔️ for loop is best when the number of iterations is known ✔️ while loop needs careful condition updates(i) to avoid infinite loops Strong loop logic = efficient programs. #Python #LearningDaily #DataScienceJourney #LearningInPublic #Consistency
To view or add a comment, sign in
-
Finding the number of subarrays with at most K distinct integers is a classic sliding window challenge. The key is to realize that for every "right" boundary, the number of valid subarrays ending there is simply the current length of the window. My approach: 🚀 Maintain a frequency map of elements within a dynamic window. 🚀 Expand the right pointer to include new elements. 🚀 If the count of distinct elements exceeds K, shrink the window from the left until it's valid again. 🚀 Add the current window size (right - left + 1) to our total count at each step. This ensures an efficient O(n) time complexity and O(k) space complexity. Check out the full implementation here: https://lnkd.in/gb-79ddZ #Coding #Algorithms #Python #DataStructures #SlidingWindow #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 8 of 365 days of code: Qn 1) Remove the duplicates from the array. Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Consider the number of unique elements in nums to be k. After removing duplicates, return the number of unique elements k. The first k elements of nums should contain the unique numbers in sorted order. The remaining elements beyond index k - 1 can be ignored. use two pointer technique. let L=1 starting from position r=1, we overwrite the number at L if nums[r-1]!=nums[r]. this process is like copy pasting the unique elements on the left side of the array, in a sorted order. #365daysOfCode #NeetCode #leetcode #DSA #python #LeetCode #ProblemSolving #Algorithms #365dayschallenge
To view or add a comment, sign in
-
-
Solving the Bitwise OR Challenge 🔢 The problem: Find the smallest 'x' such that x OR (x + 1) equals a given prime number 'p'. The Logic: 💡 The only prime number that cannot satisfy this is 2. For all other primes (which are odd), the binary representation ends in at least one '1'. 💡 The operation x OR (x + 1) essentially fills the rightmost '0' bit of 'x' with a '1'. 💡 To minimize 'x' while satisfying the condition, we look for the rightmost sequence of consecutive 1s in the prime 'p'. 💡 By flipping the highest bit of that specific trailing sequence from 1 to 0, we create our answer. Example Walkthrough: 👉 For p = 13 (1101): The trailing 1 is at position 0. Flipping it gives 1100 (12). 12 OR 13 = 13. 👉 For p = 31 (11111): The sequence of 1s is long. Flipping the bit at the "boundary" gives 01111 (15). 15 OR 16 = 31. Code Implementation: https://htmlify.me/r/u0q7 Key Takeaway: When dealing with x OR (x + 1), you are looking at how a carry bit propagates through trailing ones in binary addition! #BitManipulation #Programming #Algorithms #Python #CompetitiveProgramming #TechTips
To view or add a comment, sign in
-
-
I just tackled the classic problem of implementing K independent queues within a single array of size N! The challenge is to ensure O(1) time complexity for both enqueue and dequeue operations while maintaining optimal space efficiency. Instead of statically partitioning the array—which leads to wasted space—I used a linked-list approach within the array. By maintaining a 'next' array to track both the links between elements and a stack of free slots, the implementation allows any queue to grow as long as there is space available in the global array. This dynamic allocation ensures that no queue is blocked if the total capacity hasn't been reached. A great exercise in pointer manipulation and efficient memory management! Implementation: https://htmlify.me/r/pope #DataStructures #Coding #Python #Algorithms #SoftwareEngineering
To view or add a comment, sign in
-
-
Today I went down a rabbit hole: Queue + BFS 🕳️🐇 I started with a question: 🧐 When people say BFS, why do they always bring up a queue? Here’s what I learned: ✅ Queue basics (Python): Queue = FIFO (first in, first out) 🚶♂️➡️🚶♀️ In Python, collections.deque is the right tool because popleft() is O(1) ⚡ list.pop(0) looks similar, but it becomes O(n) because everything shifts left 🐢 ✅ What BFS is actually doing: BFS explores a graph level by level 🪜 Start node → all nodes 1 step away → then 2 steps away → and so on. That “level order” is exactly why BFS uses a queue. ✅ The big missing piece: seen/visited 👀 Without seen, cycles can make BFS loop forever 🔁😬 So marking nodes as visited (usually when enqueuing) keeps traversal correct and efficient. 🤔 Fun detail: neighbor order changes traversal order A: [B, C] vs A: [C, B] → same BFS, different visitation sequence. #Python #DSA #BFS #Queue #Deque #Algorithms #InterviewPrep #BackendEngineering
To view or add a comment, sign in
-
-
Python with DSA — Day 33 What I worked on: Prime checks: moved from naive divisibility to the √n optimization and the 6k±1 rule to cut unnecessary iterations. Time complexity intuition: compared O(n) vs O(√n) for primality tests; saw how early exits change best/worst cases. Clean loops & edge cases: handled n <= 1, negative inputs, and printed primes from 1–100 with a tight loop. Key snippet (conceptual): Idea: Only test divisors up to √n; if none divide, the number is prime. #Day33 #PythonWithDSA #DataStructures #DSAJourney #ProblemSolving #PythonProgramming #SoftwareEngineer
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge – Day 9 Problem #865: Smallest Subtree with All the Deepest Nodes (Medium) Another solid tree + DFS problem that really tests how well you understand recursion and depth tracking. 🧭 How I Approached the Question: The key was realizing that I don’t just need the depth of each subtree — I also need to know which node represents the smallest subtree containing all deepest nodes. So instead of a normal DFS, I designed a recursive function that returns two things: the height of the subtree the candidate node that could be the answer 🧠 Core Insight: For each node: Recursively compute (height, node) from the left and right subtrees Compare their heights: If left height > right height → deepest nodes are on the left If right height > left height → deepest nodes are on the right If equal → current node becomes the smallest subtree containing all deepest nodes This bottom-up approach ensures that: ✔️ Depth is calculated correctly ✔️ The smallest valid subtree is chosen automatically 🛠️ Why This Works: The deepest nodes define the maximum depth. The lowest common ancestor of all deepest nodes is exactly what the problem asks for. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(h) (recursion stack) This problem was a great reminder that: 👉 Sometimes returning more information from recursion makes the solution much cleaner. 📌 Tree problems get easier once you stop thinking top-down and start thinking bottom-up. #LeetCode #DailyCoding #BinaryTree #DFS #Recursion #ProblemSolving #DSA #Python #CodingJourney
To view or add a comment, sign in
-
-
Did you know Dyne has first-class support for GraphQL? 🕸️ Whether you prefer the modern type-hints of Strawberry or the classic feel of Graphene, Dyne provides a seamless GraphQLView. You get a built-in GraphiQL interface for testing and direct access to request/response objects in your resolvers. Pick a backend, wire your Query and Mutation into Dyne’s Schema, add a route to your view. That’s it! Query, Mutate, and explore your API: https://lnkd.in/eqEc4Tuw #Python #GraphQL #Backend #WebDev #DyneFramework #Strawberry #Graphene
To view or add a comment, sign in
-
-
I just tackled a classic "Sliding Window + Sorting" problem: Minimum Difference Between Highest and Lowest of K Scores. The Challenge: Given an array of student scores, pick k scores such that the difference between the highest and lowest is minimized. The Insight: To find the smallest gap, numbers need to be "neighbors." By sorting the array first, we can transform the problem into a simple sliding window of size k. The Strategy: 1. Sort the array (O(n log n)). 2. Slide a window of size k across the array. 3. Calculate nums[right] - nums[left] for each window. 4. Keep track of the minimum! This is a great reminder that sometimes the best way to optimize a search is to organize the data first. Implementation: https://htmlify.me/r/rj7p #LeetCode #CodingChallenge #Python #DataStructures #Algorithms #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
More from this author
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
Guys, FYI: I attempted the same question using DSU as well, and the shocking thing is, this solution took less run time as compared to DSU 😎