shriyanshi24jindal

Redundant Connection

Mar 29th, 2026
131
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 8.75 KB | None | 0 0
  1. class Solution {
  2. /**
  3.   IDEA:
  4.   Before adding edge (u, v), check if there is already a path from u to v in the graph.
  5.   If a path already exists → adding (u,v) creates a cycle → return that edge.
  6.   Otherwise → add the edge and continue.
  7.   */
  8. public int[] findRedundantConnection(int[][] edges) {
  9. int n = edges.length;
  10.  
  11. // Step-1 Create an adjacency list
  12. ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
  13. for(int i=0; i<=n; i++)
  14. {
  15. adj.add(new ArrayList<Integer>());
  16. }
  17.  
  18. // Step-2 Connect edges in adjacency list
  19. for(int[] edge : edges)
  20. {
  21. int u = edge[0];
  22. int v = edge[1];
  23.  
  24. boolean[] visited = new boolean[n+1];
  25.  
  26. // Check if path already exists
  27. if(dfs(adj, visited, u, v))
  28. {
  29. return edge;
  30. }
  31.  
  32. // Otherwise add edge
  33. adj.get(u).add(v);
  34. adj.get(v).add(u);
  35. }
  36. return new int[0];
  37. }
  38.  
  39. public boolean dfs(ArrayList<ArrayList<Integer>> adj, boolean[] visited, int node, int targetNode)
  40. {
  41. if(node == targetNode)
  42. return true;
  43.  
  44. visited[node] = true;
  45.  
  46. for(int v : adj.get(node))
  47. {
  48. if(!visited[v])
  49. {
  50. if(dfs(adj, visited, v, targetNode))
  51. return true;
  52. }
  53. }
  54. return false;
  55. }
  56. }
RAW Paste Data Copied