Solved LeetCode 110 – Balanced Binary Tree 🌳 Most people start with a brute-force approach (recomputing heights again and again), which leads to O(n²) in worst cases. Instead, I focused on an optimized bottom-up DFS (post-order traversal). 💡 Key idea: Each node returns its height if balanced Returns -1 as a sentinel if unbalanced Propagates early to avoid unnecessary computation class Solution { public boolean isBalanced(TreeNode root) { return checkHeight(root) != -1; } int checkHeight(TreeNode node){ if (node == null) return 0; int left = checkHeight(node.left); int right = checkHeight(node.right); if (left == -1 || right == -1) return -1; if (Math.abs(left - right) > 1) return -1; return Math.max(left, right) + 1; } } 🚀 Complexity: Time: O(n) Space: O(h) (recursion stack) 📌 What I learned: Combining multiple computations (height + balance) into a single traversal Using sentinel values to simplify recursion Thinking in bottom-up patterns for tree problems This pattern is widely useful in tree-based problems and even shows up in backend systems where hierarchical data needs validation. #Java #DataStructures #Algorithms #LeetCode #CodingInterview #BackendDevelopment
Mohan Lal’s Post
More Relevant Posts
-
✳️Day 39 of #100DaysOfCode✳️ Kth Smallest Element in a Sorted Matrix Here’s the step-by-step logic I followed to solve this efficiently: 1️⃣ Defining the Search Space Since the rows and columns are already sorted, we know the smallest element is at matrix[0][0] and the largest is at matrix[n-1][n-1]. Instead of searching through indices, I performed a Binary Search on the range of values between the low and high elements. 2️⃣ The "Count" Helper Function The core of this approach is a helper function that counts how many elements in the matrix are less than or equal to a specific mid value. In my current implementation, I used a nested loop approach. Optimization Tip: Since the matrix is sorted row-wise and column-wise, this count can actually be optimized to O(n) by starting from the bottom-left and moving toward the top-right! 3️⃣ Narrowing the Range Based on the count returned: If the number of elements \le mid is less than k, it means our target k^{th} element must be larger. So, I adjusted the low pointer to mid + 1. Otherwise, the target could be mid itself or something smaller, so I updated the high pointer and stored the potential answer. 4️⃣ Complexity Check By using Binary Search on the value range, we achieve a much better memory complexity than O(n^2), satisfying the problem's constraints and keeping the solution performant. Key Takeaway: Binary Search isn't just for sorted arrays; it’s a powerful tool for searching through any monotonic search space! #LeetCode #Java #DataStructures #Algorithms #CodingInterview #ContinuousLearning #SoftwareEngineering
To view or add a comment, sign in
-
-
Shallow Copy vs Deep Copy — The 2 AM Bug Trap 🛑 Most developers think they understand copying objects, until their original data mysteriously changes. That’s not a bug, that’s memory behavior biting you. → Shallow Copy Creates a new container, but nested objects are still shared (by reference) 👉 Change nested data → both copies change. Best for: Flat, simple data. → Deep Copy Creates a completely independent clone, everything is copied recursively. 👉 Change anything → original stays untouched Best for: Complex, nested structures. 💡 Rule of Thumb Shallow → when you only need a surface-level copy Deep → when you need true isolation ⚠️ The real trap: Most bugs aren’t syntax errors. They come from not understanding how data behaves in memory. If you’ve ever spent hours debugging only to realize it was a shallow copy issue. Welcome to the club 😄 #Python #Python3 #Programming #SoftwareEngineering #CleanCode #Debugging #TechTips #PythonDeveloper #BackendDevelopment
To view or add a comment, sign in
-
-
First Missing Positive — Not as Simple as It Looks At first glance, this problem looks simple. A natural instinct is to solve it using a hashmap or a set to track elements. But that approach won’t work here. The problem strictly requires: O(n) Time Complexity O(1) Space Complexity So we need a different way of thinking. The key idea is to use the input array itself as a marker instead of extra space. Approach: Clean the array Replace all negative numbers, zeros, and values greater than n with n + 1 Because the answer will always lie in the range [1, n+1] Mark presence using indices For every number num, mark the index num - 1 as negative This indicates that the number exists in the array Identify the missing number The first index that has a positive value gives the answer (index + 1) Edge case If all indices are marked, then the answer is n + 1 Why this works: We reuse the given array, so no extra space is needed. Each element is processed a constant number of times, ensuring linear time. Insight: This problem shows how constraints change your approach. A hashmap solution is straightforward, but it violates the space requirement. Sometimes the optimal solution comes from rethinking how to use the existing data instead of adding new structures. #DataStructures #Algorithms #Java #CodingInterview #ProblemSolving
To view or add a comment, sign in
-
-
🚀 rst-queue v0.1.6: Scaling Terabytes with Megabytes In a world of bloated data systems, we often find ourselves throwing more hardware at software problems. But what if our tools were engineered to be small, grounded, and incredibly powerful? Introducing rst-queue v0.1.6, a high-performance async queue system built for the modern developer who values efficiency above all else. Inspired by the psychology of the Leafcutter Ant, this project is the first major release from the Datarn initiative. Why rst-queue? Most Python-based queues are limited by the Global Interpreter Lock (GIL) and high memory overhead. rst-queue is different. By using Rust and the Crossbeam framework, we’ve built a system that: ⚡ Bypasses the GIL: Achieve true parallelism with native Rust worker pools. 🐜 Microscopic Footprint: 30-50x less memory usage than traditional message brokers. 🛡️ Dual Modes: Choose between AsyncQueue (In-memory for 1M+ items/sec) or the new AsyncPersistenceQueue (Durable storage with Sled KV). Grounded in the Kernel The secret to our speed is "Simple OS Layering." We’ve designed rst-queue to sit as close to the OS kernel as possible, utilizing direct system calls and memory-mapped I/O. This isn't just a library; it's a high-velocity data crossing (Taran) for your most critical applications. Get Started in Seconds We believe in zero-setup excellence. You can add high-performance queuing to your Python project with a single command: Bash pip install rst-queue==0.1.6 Join the Datarn Movement At Datarn, we are building a suite of "Small but Mighty" tools for data-intensive domains like B2B e-commerce and real-time analytics. rst-queue is just the beginning. Explore the project on PyPI: https://lnkd.in/d54yqdea Contribute on GitHub: https://lnkd.in/d_x3E-zj #Python #RustLang #DataEngineering #OpenSource #Efficiency #Datarn #PerformanceOptimization #SoftwareArchitecture
To view or add a comment, sign in
-
-
Half my context window was gone before I typed a single prompt. Claude Code indexed my entire monorepo at session start — Python files, Airflow DAGs, three months of task logs. Then it generated a migration that referenced a table that doesn't exist. I spent weeks rebuilding my project setup from scratch. Token usage dropped over 60%. But the real win was rework time going down significantly. Here's what actually moved the needle: - permissions.deny in settings.json — the official way to block files Claude shouldn't read. Read(./.env), Read(./airflow/logs/), Read(./.venv/). The airflow/logs line alone cut 15%. - .claudeignore — an unofficial shortcut that works like .gitignore. Not in the docs yet, but a lot of people use it. Same result, cleaner syntax. - CLAUDE.md hierarchy — root file under 200 lines. Subdirectory files load only when needed. Past 200 lines, Claude starts treating your instructions as optional. - MCP servers (BigQuery + Airflow) — live database access without pre-loading schemas into context. Deferred by default, costs almost nothing until Claude actually queries one. - Skills & agents — on-demand workflows at ~100 tokens each instead of 3,000-5,000 tokens baked into CLAUDE.md every session. - /compact and /context — the two commands I run multiple times a day to manage what's eating my context window. 30 minutes of setup. Every session after that starts lean. Full walkthrough with real configs from a data pipeline project: https://lnkd.in/gaNuSUta -- What does your Claude Code project setup look like? Are you using permissions.deny or .claudeignore — or just letting it index everything? #AICoding #SoftwareEngineering #DataEngineering #ClaudeCode #DeveloperTools #AIEngineering #SystemDesign
To view or add a comment, sign in
-
𝗗𝗮𝘆 𝟲𝟲/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 714. Best Time to Buy and Sell Stock with Transaction Fee 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Medium 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: Given an array prices where prices[i] represents the stock price on day i, and a transaction fee, find the maximum profit you can achieve. Constraints: • You can make multiple transactions • You must sell before buying again • Each transaction incurs a fixed fee 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: This problem is solved using Dynamic Programming with state optimization. Instead of maintaining a full DP table, we track two states: • buy → Maximum profit when holding a stock • sell → Maximum profit when not holding a stock • Initialization: – buy = -∞ (we haven’t bought yet) – sell = 0 • Transition for each price: – buy = max(buy, sell - price) (Either keep holding or buy today) – sell = max(sell, buy + price - fee) (Either keep not holding or sell today after paying fee) • Final answer: sell This works because at every step, we decide whether to take an action (buy/sell) or skip, while always keeping track of the best possible profit. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(n) • Space Complexity: O(1) 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Stock problems often reduce to state machines. Tracking “holding” vs “not holding” states and optimizing transitions can simplify even complex trading constraints like transaction fees. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/gz6hgkXw #Day66of75 #LeetCode75 #DSA #Java #Python #DynamicProgramming #Greedy #MachineLearning #DataScience #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
To view or add a comment, sign in
-
-
After experiencing issues with RAG demos breaking when handling real-world data, I dedicated my weekend to rebuilding the stack from scratch. Many tutorials simplify RAG to just Vector DB + Prompt, but in reality, semantic search can be noisy, and "vibes-based" retrieval often leads to hallucinations. My goal was to create a Compliance RAG pipeline capable of managing rigid, regulatory language without failure. Here’s the "v1" of my personal project and the architecture behind it: The Build: 📌The Hybrid Layer: I combined Qdrant with BM25. This approach ensures that if a compliance document references "Section 402.b," keyword search can capture it even if an embedding might miss it. 📌The Reranker: I incorporated a Cross-Encoder layer. Although slower than a vector lookup, it guarantees that the LLM only processes the most relevant context, significantly enhancing accuracy. 📌The Frontend: I developed a decoupled React + Vite UI utilizing Server-Sent Events (SSE) to prioritize real-time token streaming and eliminate frustrating spinning loaders. The Tech Stack: - Language: Python (FastAPI), Langgraph, - Embeddings: BGE + OpenAI. - Database: Qdrant(Vector Database) - Deployment: Successfully launched on AWS EC2 using Nginx, Docker and a GitHub Actions pipeline. 🚀Project Demo link: https://aryangupta.work/ 🧠 What I Learned: The LLM is actually the simplest component of the stack—serving primarily as a formatter. The true "intelligence" resides in the retrieval and ranking logic. If your retrieval is only 60% accurate, your LLM will also be limited to that accuracy, regardless of prompt quality. I'm pleased with the reranking latency results, though I'm still fine-tuning the hybrid weights. For those developing RAG systems: How do you manage the latency trade-off of a Cross-Encoder versus the precision benefits? #BuildInPublic #RAG #Python #FastAPI #MachineLearning #LLMOps #Qdrant #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Cracked LeetCode 18 : 4Sum — From Naive to Optimal Approach Today I worked on the classic 4Sum problem — finding all unique quadruplets that sum to a target. 🔴 Naive Approach (Brute Force) Think of checking every possible quadruplet: Use 4 loops (i, j, k, l) Check if sum == target Store unique results using a set ⏱️ Time Complexity: O(n⁴) 👉 Works, but too slow for large inputs. 🟡 Better Approach (Hashing) Fix 2 elements Use a HashSet for remaining 2 elements (like 2Sum) ⏱️ Time Complexity: O(n³) 👉 Faster, but still not optimal. 🟢 Optimal Approach (Sorting + Two Pointers) 💡 Idea: Sort the array Fix first two numbers (i, j) Use two pointers (k, l) to find remaining pair ⏱️ Time Complexity: O(n³) But much faster in practice due to pruning & skipping duplicates. 💻 Pseudo Code (Easy to Understand): sort array for i from 0 to n-1: skip duplicates for i for j from i+1 to n-1: skip duplicates for j k = j + 1 l = n - 1 while k < l: sum = arr[i] + arr[j] + arr[k] + arr[l] if sum == target: store answer k++, l-- skip duplicates for k and l else if sum < target: k++ else: l-- 🔥 Key Interview Insight 👉 “Sort + Fix elements + Reduce to 2Sum using two pointers” #DataStructures #Algorithms #Java #LeetCode #CodingInterview #100DaysOfCode
To view or add a comment, sign in
-
Floyd's cycle detection algorithm finally clicked today — and the math had nothing to do with it. The problem: LeetCode 287, Find the Duplicate Number. Constraints rule out sorting, hash sets, and modifying the input. The trick is to read the array as a linked list and detect a cycle. I'd seen the textbook explanation before. The algebra (F = (k−1)C + b) made sense on paper but never gave me a mental picture I could rebuild from scratch. What unstuck me was an analogy: the lollipop. Here's the version that stuck: 1. Don't iterate the array as 0, 1, 2, 3, 4. Iterate by values — nextIndex = nums[currentIndex]. This turns the array into a chain. 2. Because there's a duplicate, two indices end up pointing to the same next index. That creates a cycle. The overall shape: a straight stick from index 0 to the cycle entrance, then a loop at the end. A lollipop. 3. Run two pointers from index 0 — slow (1 step) and fast (2 steps). Inside the loop, fast catches slow at some meeting point. 4. The non-obvious part: the distance from the meeting point forward around the loop back to the entrance matches the distance from the start to the entrance. (Whole laps cancel out — but the math is optional once you see the picture.) 5. Reset one pointer to the start. Leave the other at the meeting point. Move both one step at a time. They collide exactly at the entrance — and the entrance index is the duplicate. O(n) time, O(1) space, no input mutation. All three problem constraints satisfied. The bigger lesson, especially for senior interview prep: when an algorithm feels like memorization, you don't have the picture yet. Find the picture, and the proof becomes something you can rebuild on the fly instead of cram. The notation is just the picture wearing a tie. #Java #DataStructures #Algorithms #InterviewPrep #LeetCode
To view or add a comment, sign in
-
🚀 Solved: LeetCode 779 — K-th Symbol in Grammar This problem turned out to be a perfect example of how one problem can be solved at multiple levels of thinking — from brute force to mathematical optimization. I implemented 5 different approaches to deeply understand the pattern: 🔹 1. Brute Force Build the entire row using string transformation Time/Space: O(2ⁿ) → Not scalable 🔹 2. Iterative (Flip Counting) Traverse upward and count how many times the value flips Time: O(log n), Space: O(1) 🔹 3. Bit Manipulation (Optimized) Key insight: result = parity of set bits in (k - 1) Code: Integer.bitCount(k - 1) % 2 Clean, fast, and interview-ready 🔹 4. Recursive (Top-Down) Find parent and decide flip based on position Builds strong intuition for recursion trees 🔹 5. Tail Recursion Track flips as a parameter (no work after recursion) Helps understand recursion → iteration conversion 💡 Key Insight: Instead of building the entire string, we only track the path from root to the k-th position. 👉 Final realization: Answer = number of right moves (or set bits in k-1) % 2 ⏱ Complexity: Brute Force → O(2ⁿ) Optimized Approaches → O(log n) This problem really strengthened my understanding of: ✔ Recursion vs Tail Recursion ✔ Optimization thinking ✔ Bit manipulation ✔ Converting recursive logic into iterative solutions 🙏 Special thanks to Sir Anuj Kumar (a.k.a CTO Bhaiya on YouTube) for the clear and conceptual explanation: https://lnkd.in/dQBtSyxK 📌 LeetCode: https://lnkd.in/d6CKa-BN 📌 GitHub: https://lnkd.in/gnEfmGAg Recursion is not easy — but with consistent practice, patterns start becoming clear. #Java #DSA #LeetCode #Recursion #Algorithms #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