🚀 DSA Challenge – Day 84 Problem: Reachable Nodes in a Restricted Tree 🌲🚫 This problem was a perfect blend of graph traversal and constraint handling, where we must carefully explore a tree while avoiding restricted nodes. 🧠 Problem Summary: You are given a tree with n nodes (0-indexed) and a list of edges that describe the connections between them. Some nodes are restricted, meaning you cannot visit or pass through them. Starting from node 0, the goal is to determine how many nodes are reachable without visiting any restricted ones. ⚙️ My Approach: 1️⃣ Build an adjacency list representation of the tree. 2️⃣ Store all restricted nodes in a set for quick lookup. 3️⃣ Use Depth-First Search (DFS) to traverse the graph, skipping restricted or already visited nodes. 4️⃣ Accumulate a count of all valid reachable nodes. 📈 Complexity: Time: O(n) → Each node and edge is processed once. Space: O(n) → For adjacency list, recursion stack, and visited set. ✨ Key Takeaway: Even simple DFS problems become interesting when constraints are introduced. Efficient use of sets and recursion can elegantly handle conditions like restricted traversal in trees or graphs. 🌿 🔖 #DSA #100DaysOfCode #LeetCode #GraphTheory #TreeTraversal #DFS #Python #ProblemSolving #CodingChallenge #InterviewPrep #Algorithms #EfficientCode #TechCommunity #CodeEveryday #LearningByBuilding
"Reachable Nodes in a Restricted Tree: A DFS Challenge"
More Relevant Posts
-
🚀 Day 29 DSA Challenge – Problem 704: Binary Search A timeless classic — the foundation of efficient searching algorithms 🔍 🎯 Problem Statement: Given a sorted array nums and an integer target, find the index of target using an algorithm with O(log n) time complexity. If target doesn’t exist, return -1. 🧩 How I Solved It: Used the Binary Search technique — repeatedly dividing the search space in half. Initialized two pointers, left and right, representing the current search range. Found the middle index mid, compared nums[mid] with target: If equal → returned mid. If smaller → shifted the left boundary rightward. If greater → moved the right boundary leftward. Continued until left > right, meaning the element isn’t found. ⚙️ Performance Stats: ⏱ Runtime: 0ms (⚡ beats 100%) 💾 Memory: 13.48MB (beats 31.70%) ✅ Testcases Passed: 47 / 47 ✨ Insight: Binary Search perfectly demonstrates divide-and-conquer at its best — turning linear scans into logarithmic efficiency 🚀 #LeetCode #Problem704 #BinarySearch #Algorithm #DSA #DivideAndConquer #Python #100DaysOfCode #CodingChallenge
To view or add a comment, sign in
-
-
🌳 DSA Challenge – Day 99 Problem: Balanced Binary Tree ⚖️🌲 This classic tree problem tests your understanding of recursion, depth-first search, and how to efficiently check balance conditions in binary trees. 🧠 Problem Summary: A height-balanced binary tree is one in which the height of the two subtrees of every node never differs by more than 1. Your task: Given the root of a binary tree, determine whether it is height-balanced. ⚙️ My Approach: 1️⃣ Use a recursive DFS helper util() to traverse the tree. 2️⃣ For each node, compute: Whether its left and right subtrees are balanced. The maximum depth of its left and right subtrees. 3️⃣ If at any point the height difference exceeds 1, return False. 4️⃣ The function returns both a boolean (isBalanced) and an integer (height). 💡 Optimization Insight: Instead of computing the height in a separate pass (which would make it O(n²)), this approach combines balance checking and height calculation in one DFS traversal, resulting in O(n) time complexity. 📈 Complexity Analysis: Time Complexity: O(n) — Each node is visited once. Space Complexity: O(h) — Recursion stack, where h is the height of the tree. ✨ Key Takeaway: Efficient recursion patterns often come from returning multiple values — combining partial results avoids redundant computation and keeps solutions elegant. 🔖 #DSA #100DaysOfCode #BinaryTree #LeetCode #ProblemSolving #CodingChallenge #Python #Algorithms #Recursion #TreeTraversal #TechCommunity #LearningEveryday
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 90 Problem: Single Element in a Sorted Array ⚙️🔍 This problem was a clever application of binary search where understanding the index patterns of paired elements was the key to achieving logarithmic efficiency. 🧠 Problem Summary: You are given a sorted array where every element appears exactly twice, except for one element that appears only once. Your task: return that single element in O(log n) time and O(1) space. ⚙️ My Approach: 1️⃣ Used binary search to narrow down the segment containing the single element. 2️⃣ Checked if the middle element breaks the pairing rule — if so, that’s our unique number. 3️⃣ Observed the pattern: Before the single element, pairs start at even indices. After it, pairs start at odd indices. 4️⃣ Used this parity observation to adjust the search boundaries efficiently. 📈 Complexity: Time: O(log n) → Binary search halves the search space each step. Space: O(1) → Constant space used. ✨ Key Takeaway: Sometimes, the structure of sorted pairs reveals more than meets the eye — a small parity trick transforms a linear scan into a logarithmic search. ⚡ 🔖 #DSA #100DaysOfCode #LeetCode #ProblemSolving #BinarySearch #Algorithms #CodingChallenge #Python #Optimization #EfficientCode #TechCommunity #InterviewPrep #LearningByBuilding #CodeEveryday
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 80 Problem: Maximum Distance Between Valid Pairs 🌊📏 Today’s problem tested the combination of binary search and array monotonicity — finding the farthest valid pair between two non-increasing arrays! 🧠 Problem Summary: We’re given two non-increasing arrays, nums1 and nums2. A pair (i, j) is valid if: i ≤ j, and nums1[i] ≤ nums2[j]. The goal is to find the maximum distance (j - i) among all valid pairs. ⚙️ My Approach: 1️⃣ Iterate through each element in nums1. 2️⃣ Use binary search on nums2 to find the farthest valid index satisfying the condition. 3️⃣ Keep track of the maximum j - i distance encountered. This solution leverages the sorted (non-increasing) property of arrays for logarithmic efficiency. 📈 Complexity: Time: O(n log m) → For each element in nums1, a binary search on nums2. Space: O(1) → Only a few variables used. ✨ Key Takeaway: Sometimes, monotonic properties allow you to blend binary search with iteration — turning what looks like a brute-force problem into a clean and efficient search-based solution. ⚡ 🔖 #DSA #100DaysOfCode #LeetCode #ProblemSolving #Algorithms #BinarySearch #TwoPointers #CodingChallenge #Python #InterviewPrep #TechCommunity #Optimization #EfficientCode #CodeEveryday
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 85 Problem: Check if All Integers in a Range Are Covered ✅📏 This problem was an elegant use of the Prefix Sum technique, where I used range updates to efficiently check coverage over an interval. 🧠 Problem Summary: You are given several inclusive integer intervals and a target range [left, right]. You must verify if every integer within [left, right] is covered by at least one of the given intervals. ⚙️ My Approach: 1️⃣ Initialize an array line to track coverage at each integer position. 2️⃣ For every range [a, b], increment line[a] and decrement line[b + 1] — this marks the start and end of coverage. 3️⃣ Convert line into a prefix sum array, so each position reflects how many intervals cover that number. 4️⃣ Finally, iterate through [left, right] to ensure each integer has coverage (> 0). 📈 Complexity: Time: O(n + 52) → Linear scan and prefix sum computation. Space: O(52) → Fixed-size array since ranges are small. ✨ Key Takeaway: Prefix sum is not just for subarray sums — it’s a powerful trick for range marking and coverage problems, offering O(1) updates and O(n) verification. ⚡ 🔖 #DSA #100DaysOfCode #LeetCode #PrefixSum #RangeUpdate #ProblemSolving #Algorithms #CodingChallenge #Python #EfficientCode #Optimization #TechCommunity #InterviewPrep #CodeEveryday #LearningByBuilding
To view or add a comment, sign in
-
-
🚀 DSA Progress – Day 112 ✅ Problem #560: Subarray Sum Equals K 🧠 Difficulty: Medium | Topics: Array, Prefix Sum, Hash Map 🔍 Approach: Implemented the Prefix Sum + Hash Map technique to efficiently count subarrays whose sum equals k. Step 1 (Prefix Sum): Maintain a running sum (prefix_sum) as we iterate through the array. Step 2 (Check for Required Sum): For each prefix_sum, check if (prefix_sum - k) exists in the hashmap. If yes → it means a subarray ending at the current index sums to k. Step 3 (Store Frequency): Use a dictionary (mp) to store how many times each prefix sum has appeared. This allows counting multiple subarrays efficiently. 🕒 Time Complexity: O(n) 💾 Space Complexity: O(n) (for hashmap storage) 📁 File: https://lnkd.in/g7acMKiA 📚 Repo: https://lnkd.in/g8Cn-EwH 💡 Learned: This problem strengthened my understanding of how prefix sums can simplify subarray-related questions. Instead of manually checking every subarray, we convert the problem into recognizing a pattern using previous sums. This is a powerful technique that shows up frequently in interview-level array problems. ✅ Day 112 complete — counted hidden subarrays like a pro! 🔢🎯✨ #LeetCode #DSA #Python #Arrays #PrefixSum #HashMap #Algorithm #DailyCoding #InterviewPrep #GitHubJourney #ProblemSolving
To view or add a comment, sign in
-
Day 62: Recover Binary Search Tree (BST) 🌳 I'm continuing my journey on Day 62 of #100DaysOfCode with a challenging BST problem: "Recover Binary Search Tree." The task is to fix a BST where exactly two nodes have been swapped by mistake, all without changing the tree's structure. The key insight relies on the property of Inorder Traversal of a BST, which always yields nodes in ascending order. Inorder Traversal: I first perform a standard inorder traversal (using recursion) to store the node values in an ascending list (inorder). Finding Swapped Nodes: I then iterate through the inorder list to find the two misplaced nodes. A violation occurs when inorder[i-1] > inorder[i]. The first misplaced node (first) is the larger element of the first violation. The second misplaced node (second) is the smaller element of the last violation. Correction: Finally, I swap the values of the two nodes found in the original tree. This method achieves an O(n) time complexity and O(n) space complexity (due to storing the inorder array). My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #BST #InorderTraversal #100DaysOfCode #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Solving Binary Subarray With Sum — From Brute Force to Optimal I recently solved LeetCode 930: Binary Subarray With Sum, and it turned out to be a great learning path across multiple techniques 💡 Problem: Count subarrays in a binary array whose sum equals a target (goal). My approach evolution: 1️⃣ Brute Force (O(n²)) – Check all (i, j) pairs. 2️⃣ Prefix Sum Array – Simplified sum calculation but still O(n²). 3️⃣ Prefix Sum + HashMap (O(n)) – Store prefix frequencies to count valid subarrays efficiently. 4️⃣ Sliding Window – For binary arrays, maintain subarray sum dynamically. 5️⃣ Special Case (goal == 0) – Count zero stretches combinatorially: k * (k + 1) / 2. ✅ Final solution combines: Prefix Sum Frequency (for goal > 0) Zero Stretch Counting (for goal = 0) Key takeaway: From brute force to optimized O(n), this problem teaches how prefix sums, hash maps, and combinatorics work together for elegant problem-solving. #LeetCode #ProblemSolving #DataStructures #Algorithms #CodingJourney #PrefixSum #SlidingWindow #Python
To view or add a comment, sign in
-
-
The best way to learn a system is to build it, so I put together a small RAG backend to explore the fundamentals. Built with Python + FastAPI + ChromaDB + OpenRouter, it keeps things simple and clear: Upload documents (.txt, .md, .pdf) Embed + store locally in a vector database /ask endpoint with answers grounded only in the provided files Modular FastAPI layout (indexing, retrieval, services) Lightweight logging and tests No heavy frameworks, just the core mechanics of retrieval-augmented generation to understand how LLMs interact with external context. Repo: https://lnkd.in/daiYrskH If you’ve worked with RAG and have ideas for improvements or evaluation approaches, I’m open to suggestions. #Python #FastAPI #Backend #ChromaDB #LLM #AIEngineering #OpenRouter #RAG
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 88 Problem: Count Subarrays with Sum Equal to K 📊🔥 This problem was an excellent exercise in using prefix sums and hashmaps to efficiently track cumulative sums and identify subarrays that meet a specific target. 🧠 Problem Summary: Given an array of integers nums and an integer k, find the total number of contiguous subarrays whose sum equals k. ⚙️ My Approach: 1️⃣ Maintain a running prefix sum s as we iterate through the array. 2️⃣ Use a hashmap hashMap to store how many times each prefix sum has appeared. 3️⃣ For each element, check if (s - k) exists in the hashmap — if yes, it means a subarray summing to k ends at the current index. 4️⃣ Update the hashmap with the new prefix sum count. 📈 Complexity: Time: O(n) — each element is processed once. Space: O(n) — for storing prefix sums in the hashmap. ✨ Key Takeaway: Prefix sum combined with a hashmap is a powerful technique to convert subarray problems from O(n²) brute force into elegant O(n) solutions. ⚡ 🔖 #DSA #100DaysOfCode #LeetCode #ProblemSolving #HashMap #PrefixSum #CodingChallenge #Python #Algorithms #EfficientCode #InterviewPrep #TechCommunity #CodeEveryday #LearningByBuilding
To view or add a comment, sign in
-
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