← L&T Mindtree bank

L&T Mindtree · Question 60 · Graphs

Course Schedule (Cycle Detection)

GraphsJavacode⏱ O(v+e)💾 O(v+e)
Service-based

Problem

You are given number of courses and prerequisites. Check if you can finish all courses.

Approach

Kahn's BFS: emit zero-indegree courses; leftovers mean a cycle.

Time O(v+e)Space O(v+e)

How it works

  1. 1Build the graph with indegree counts.
  2. 2Unprocessed courses sit in a cycle.

Sample input / output

Input:
numCourses = 2, prerequisites = [[1, 0], [0, 1]]
Output:
false

Constraints

1 <= numCourses <= 2000.

Solution — read it, then walk it

Time O(v+e)Space O(v+e)Loops 5Branches 2Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static booleancanFinish(int numCourses,int[][] prerequisites)List<List<Integer>> graph =new ArrayList<>()for (int i = 0; i <numCourses; i++)graph.add(ne…DEFINE [] indegree = newint[numCourses]for (int[] pre :prerequisites)graph.get(pre[1]).add(pre[0])indegree[pre[0]]++Queue<Integer> q = newLinkedList<>()for (int i = 0; i <numCourses; i++)if (indegree[i] == 0)q.add(i)DEFINE count = 0while (!q.isEmpty())DEFINE course = q.poll()count++for (int next :graph.get(course))if (--indegree[next]== 0) q.add(next)RETURN count == numCoursesDEFINE static voidmain(String[] args)System.out.println(canFinish(2,new int[][]{{1, 0}, {0,1}}))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/22

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits