🚀 Day 9/100 — 💻 Problem: Detect Cycle in a Directed Graph Given a graph, check if it contains a cycle Concept: DFS + Recursion Stack — Traverse each node using DFS — Track visited nodes — Maintain a recursion stack — If a node is visited again in the same path → cycle detected def has_cycle(graph): visited = set() rec_stack = set() def dfs(node): if node in rec_stack: return True if node in visited: return False visited.add(node) rec_stack.add(node) for neighbor in graph[node]: if dfs(neighbor): return True rec_stack.remove(node) return False for node in graph: if dfs(node): return True return False What I learned: Not all problems are about values… some are about relationships. Tracking the path is as important as visiting nodes Time Complexity: O(V + E) Graph problems are all about how things are connected! #100DaysOfCode #DSA #Graphs #DFS #CodingInterview #ProblemSolving #PlacementPrep
Detect Cycle in a Directed Graph using DFS
More Relevant Posts
-
Day 67/150 🚀 LeetCode 912: Sort an Array 🧠 Problem Given an integer array nums, sort the array in ascending order without using built-in sorting functions. 📌 Example Input → nums = [5,2,3,1] Output → [1,2,3,5] 💡 Approach (Merge Sort) • Divide array into two halves • Recursively sort left half • Recursively sort right half • Merge sorted halves ⚡ Example Walkthrough [5,2,3,1] → Divide → [5,2] [3,1] → Sort → [2,5] [1,3] → Merge → [1,2,3,5] ⏱ Time Complexity O(n log n) 📦 Space Complexity O(n) ✅ Result: Accepted ⚡ Runtime: 70 ms (Beats 60.61%) Strengthening sorting fundamentals with Merge Sort 🔥 Consistency continues — Day 67 complete 🚀 #Day67 #LeetCode #DSA #MergeSort #Sorting #CodingJourney #ProblemSolving #SoftwareEngineering #TopInterview150
To view or add a comment, sign in
-
-
Day 46 of DSA Find the nearest index having the same value for given queries. Initial Thought (Brute Force): For each query: Move left & right Find nearest same element Time Complexity: O(n²) → Not efficient Optimized Approach: Instead of checking every time, I thought: Why not store positions of each element first? So I used: unordered_map<int, vector<int>> to store indices Example: nums = [1,2,1,3,1] 1 → [0,2,4] For each query: Get all indices of that value Use binary search (lower_bound) Check nearest left & right Sometimes the nearest element comes from wrapping around the array. What I Learned: Preprocessing can reduce complexity Binary search + hashmap is a powerful combo Always check edge cases like circular arrays Time Complexity: O(n log n) #DSA #Cpp #LeetCode #CodingJourney #ProblemSolving #Day46
To view or add a comment, sign in
-
-
🧠 Understanding Binary Trees finally clicked for me today. I used to feel confused about DFS traversals — especially what actually happens when we write: 👉 dfs(node.left) 👉 dfs(node.right) Today it made sense. When we call dfs(node.left), we're not just accessing a value — we're traversing the entire left subtree recursively. Same with dfs(node.right) → it explores the entire right subtree. 💡 The biggest insight: Every node becomes a decision point: - Do something with the current node - Then move left - Then move right That’s all DFS really is. 🚀 Example: Counting total nodes in a tree function countNodes(root) { if (!root) return 0; return 1 + countNodes(root.left) + countNodes(root.right); } 👉 1 = current node 👉 left subtree count 👉 right subtree count 📌 What I learned: - Recursion = breaking a big problem into smaller identical problems - DFS is just a pattern, not something to memorize - Traversals (inorder, preorder, postorder) are just about WHEN you process the node This changed how I think about trees completely. Next: applying this to solve more problems. . . . . #DSA #BinaryTree #Recursion
To view or add a comment, sign in
-
🚀 Dr. G. Vishwanathan Challenge | Day 16 Solved: Maximum Depth of Binary Tree 💡 Key Insights: Used recursion (DFS) to compute depth of left and right subtrees. Depth of a node = 1 + max(left height, right height). Base case (root == NULL) ensures correct termination. Problem reinforces understanding of tree height and recursion flow. ⏱️ Complexity: Time Complexity: O(n) → each node is visited once Space Complexity: O(h) → recursion stack (h = height of tree) ⚡ Takeaway: Many tree problems reduce to breaking them into smaller subtrees. Clear recursive thinking makes solving such problems straightforward and efficient. #DrGVishwanathanChallenge #DSA #BinaryTree #Recursion #DFS #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 25 of my Data Structures & Algorithms journey 🚀 Solved: Median of Two Sorted Arrays (LeetCode 4) 💡 Key Takeaway: Learned how binary search can be applied on partitions instead of elements, helping find the median in logarithmic time without merging arrays. ⚡ What I improved: • Binary Search on answer space • Handling edge cases with INT_MIN & INT_MAX • Understanding partition logic deeply #LeetCode #DSA #BinarySearch #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Cracked "Number of Longest Increasing Subsequences" — and learned something deeper along the way! Initially, I approached the problem using tabulation (bottom-up DP) and then traversed the DP array to count the number of LIS. While the logic felt correct, it unfortunately led to TLE. That’s when I paused and re-analyzed the problem more carefully. Key Insight: It’s not just about finding the length of LIS — we also need to track the count of LIS ending at each index. This led me to a refined approach: Use DP twice (or maintain two DP arrays): length[i] → Length of LIS ending at index i count[i] → Number of LIS ending at index i While iterating: If a longer subsequence is found → update both length and count If another subsequence of the same length is found → increment count This optimization avoids redundant computations and ensures we only build what’s necessary — no extra traversal needed! Takeaway: Sometimes, the difference between TLE and AC is not complexity alone, but modeling the problem correctly. Every DP problem teaches you something new — this one reinforced the importance of tracking multiple states simultaneously. #DataStructures #DynamicProgramming #LeetCode #ProblemSolving #CodingJourney #LearnByDoing #Optimization #TechGrowth
To view or add a comment, sign in
-
-
🧠 Day 202 — Minimum Spanning Tree (Prim’s Algorithm) 🌳⚡ Today I solved Minimum Spanning Tree (MST) using Prim’s Algorithm, a core concept in graph optimization. 📌 Problem Goal Given a weighted undirected graph: ✔️ Connect all vertices ✔️ Minimize total edge weight ✔️ No cycles allowed 🔹 Core Idea Grow the tree step by step: 👉 Always pick the minimum weight edge connecting a new node 🔹 Approach 1️⃣ Build adjacency list 2️⃣ Use a min-heap (priority queue) 3️⃣ Start from any node (e.g., 0) 4️⃣ Pick the smallest edge → add to MST 5️⃣ Mark node as visited and push its neighbors 🔹 Key Insight ✔️ Greedy choice → always take smallest edge ✔️ Avoid revisiting nodes to prevent cycles ✔️ Heap ensures optimal edge selection 🧠 Key Learning ✔️ Prim’s = BFS + Priority Queue mindset ✔️ Works well with adjacency list representation ✔️ MST problems are about optimization, not paths 💡 Today’s Realization Graph algorithms now feel like a complete system: • BFS / DFS → Traversal • Dijkstra → Shortest Path • Bellman-Ford → Negative weights • Floyd-Warshall → All pairs • Prim’s → Minimum Spanning Tree Different goals, same graph foundation. 🚀 Momentum Status: Graph concepts are now deeply connected. On to Day 203. #DSA #Graphs #MinimumSpanningTree #PrimsAlgorithm #LeetCode #Java #CodingJourney #ConsistencyWins
To view or add a comment, sign in
-
-
🚀 Day 84 of #100DaysOfCode Today, I solved LeetCode 785 – Is Graph Bipartite?, a fundamental graph problem that focuses on graph coloring and traversal. 💡 Problem Overview: Given an undirected graph, the task is to determine whether it can be divided into two sets such that no two adjacent nodes belong to the same set. 🧠 Approach: ✔️ Applied BFS/DFS traversal ✔️ Used a coloring technique (2 colors) to assign nodes into two groups ✔️ Ensured that no adjacent nodes share the same color ✔️ If a conflict occurs → graph is not bipartite ⚡ Key Takeaways: Bipartite problems are based on 2-coloring logic BFS/DFS both can be used effectively Graph coloring is a powerful concept in many problems 📊 Complexity Analysis: Time Complexity: O(V + E) Space Complexity: O(V) Strengthening core graph concepts step by step 🚀 #LeetCode #100DaysOfCode #DSA #Graphs #BFS #DFS #GraphTheory #ProblemSolving #CodingJourney #SoftwareDevelopment #InterviewPrep
To view or add a comment, sign in
-
-
🚀 Day 24/100 — Problem: Detects if a graph has a cycle Using Disjoint Set (Union-Find) Concept: Union-Find - Each node belongs to a set - Union → connect two nodes - Find → check root parent class UnionFind: def __init__(self, n): self.parent = list(range(n)) def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) # path compression return self.parent[x] def union(self, x, y): px, py = self.find(x), self.find(y) if px == py: return True # cycle detected self.parent[py] = px return False What I learned: Efficient grouping helps solve connectivity problems Path compression makes it fast. Time Complexity: ~O(α(n)) #100DaysOfCode #DSA #UnionFind #Graphs #CodingInterview #ProblemSolving #PlacementPrep #LearnInPublic
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🧩 Problem: XOR After Range Multiplication Queries I You are given: An array nums a list of queries, where each query contains: l → left index , r → right index , k → step size , v → multiplication value 🎯 Goal For each query: Start from index l Multiply elements at indices: l, l+k, l+2k, ... ≤ r by value v (mod 1e9+7) After processing all queries, return the XOR of all elements in the updated array. 🧠 Key Intuition This problem combines: Range-based updates with step jumps Modulo arithmetic Bitwise XOR 🛠 Approach 1️⃣ Iterate through each query: Extract l, r, k, v 2️⃣ For each query: Start from index l Jump in steps of k Update elements: nums[idx] = (nums[idx] × v) % mod 3️⃣ After processing all queries: Compute XOR of all elements in nums 📈 Complexity Analysis Time Complexity: O(Q * n) Space Complexity: O(1) 🔗 Problem https://lnkd.in/ddyZDs8c 💻 Solution https://lnkd.in/dbTBKXzf #LeetCode #Cpp #DSA #Algorithms #BitManipulation #Arrays #ProblemSolving #CodingChallenge #LeetCodeDailyChallenge #CompetitiveProgramming #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