Posts

Showing posts from January, 2025

Important Graph Algorithms for Problem solving

Image
  Below is the important Graph Algorithms for problem solving Algorithms Cycle Detection Algorithm  For Directed graph Cycle can be detected using : 1) DFS-Based Cycle Detection using  color marking (visited array)     void dfs(node):       mark visited       for neighbor:          if not visited:              dfs(neighbor)        stack.push(node) 2) Kahn’s Algorithm : Build the Graph → Create an adjacency list from the prerequisites array. Compute In-Degree → Count the number of prerequisites (incoming edges) for each course. Start BFS with Zero In-Degree Nodes → Add all courses with zero prerequisites to a queue. Process Courses in BFS Order → Remove edges and reduce in-degrees. Check if All Courses Were Taken → If all courses were processed, return true ; otherwise, there’s a cycle.     // Simple idea of Kahn's: while (queue is n...

Meeting Room 1 and Meeting Room 2 of Leetcode

                                    Meeting Room 1 and Meeting Room 2 of Leetcode 252. Meeting Rooms Given an array of meeting time  intervals  where  intervals[i] = [start i , end i ] , determine if a person could attend all meetings. Example 1: Input: intervals = [[0,30],[5,10],[15,20]] Output: false Example 2: Input: intervals = [[7,10],[2,4]] Output: true Solution: Sort according to Ending time. public boolean canAttendMeetings ( int [][] intervals ) { Arrays . sort (intervals, ( int [] a, int [] b) -> { return a[ 1 ] - b[ 1 ]; }); int n = intervals . length ; for ( int i = 1 ;i<n;i++){ int st = intervals[i][ 0 ]; int en = intervals[i][ 1 ]; if (st < intervals[i- 1 ][ 1 ]){ return false ; } } return true ; }