From ef6764c5d66cf36b34bebf64813f6126a1d7e88c Mon Sep 17 00:00:00 2001 From: mjk22071998 Date: Fri, 10 Oct 2025 23:37:11 +0500 Subject: [PATCH 01/10] feat: BinaryTreeToString.java Added with tests --- .../trees/BinaryTreeToString.java | 55 ++++++++++++++++++ .../trees/BinaryTreeToStringTest.java | 57 +++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java create mode 100644 src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeToStringTest.java diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java new file mode 100644 index 000000000000..03c38a07b226 --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java @@ -0,0 +1,55 @@ +package com.thealgorithms.datastructures.trees; + +/** + * Converts a Binary Tree to its string representation using preorder traversal. + * Rules: + * - Each node is wrapped in parentheses (val) + * - Include "()" when a right child exists without a left child + * - Skip empty parentheses otherwise + * + * Example: + * Input: 1 + * / \ + * 2 3 + * \ + * 4 + * Output: "1(2()(4))(3)" + * + * Matches the logic from LeetCode 606, using a DFS traversal. + */ +public class BinaryTreeToString { + + private StringBuilder sb; + + public String tree2str(BinaryTree.Node root) { + if (root == null) { + return ""; + } + + sb = new StringBuilder(); + dfs(root); + // remove the first and last parentheses + return sb.substring(1, sb.length() - 1); + } + + private void dfs(BinaryTree.Node node) { + if (node == null) { + return; + } + + sb.append("(").append(node.data); + + if (node.left != null) { + dfs(node.left); + } + + if (node.right != null && node.left == null) { + sb.append("()"); + dfs(node.right); + } else if (node.right != null) { + dfs(node.right); + } + + sb.append(")"); + } +} diff --git a/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeToStringTest.java b/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeToStringTest.java new file mode 100644 index 000000000000..2461fd74143d --- /dev/null +++ b/src/test/java/com/thealgorithms/datastructures/trees/BinaryTreeToStringTest.java @@ -0,0 +1,57 @@ +package com.thealgorithms.datastructures.trees; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * Tests for the BinaryTreeToString class. + */ +public class BinaryTreeToStringTest { + + @Test + public void testTreeToStringBasic() { + BinaryTree tree = new BinaryTree(); + tree.put(1); + tree.put(2); + tree.put(3); + tree.put(4); + + BinaryTreeToString converter = new BinaryTreeToString(); + String result = converter.tree2str(tree.getRoot()); + + // Output will depend on insertion logic of BinaryTree.put() + // which is BST-style, so result = "1()(2()(3()(4)))" + Assertions.assertEquals("1()(2()(3()(4)))", result); + } + + @Test + public void testSingleNodeTree() { + BinaryTree tree = new BinaryTree(); + tree.put(10); + + BinaryTreeToString converter = new BinaryTreeToString(); + String result = converter.tree2str(tree.getRoot()); + + Assertions.assertEquals("10", result); + } + + @Test + public void testComplexTreeStructure() { + BinaryTree.Node root = new BinaryTree.Node(10); + root.left = new BinaryTree.Node(5); + root.right = new BinaryTree.Node(20); + root.right.left = new BinaryTree.Node(15); + root.right.right = new BinaryTree.Node(25); + + BinaryTreeToString converter = new BinaryTreeToString(); + String result = converter.tree2str(root); + + Assertions.assertEquals("10(5)(20(15)(25))", result); + } + + @Test + public void testNullTree() { + BinaryTreeToString converter = new BinaryTreeToString(); + Assertions.assertEquals("", converter.tree2str(null)); + } +} From 5be7d1be8a39c381a40e88911edad14f52f9e1f2 Mon Sep 17 00:00:00 2001 From: mjk22071998 Date: Fri, 10 Oct 2025 23:45:02 +0500 Subject: [PATCH 02/10] fix: javadoc added to BinaryTreeToString --- .../trees/BinaryTreeToString.java | 70 +++++++++++++++---- 1 file changed, 56 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java index 03c38a07b226..c31abf4e5f15 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java @@ -1,26 +1,58 @@ package com.thealgorithms.datastructures.trees; /** - * Converts a Binary Tree to its string representation using preorder traversal. - * Rules: - * - Each node is wrapped in parentheses (val) - * - Include "()" when a right child exists without a left child - * - Skip empty parentheses otherwise + * Utility class to convert a {@link BinaryTree} into its string representation. + *

+ * The conversion follows a preorder traversal pattern (root → left → right) + * and uses parentheses to denote the tree structure. + * Empty parentheses "()" are used to explicitly represent missing left children + * when a right child exists, ensuring the structure is unambiguous. + *

* - * Example: - * Input: 1 - * / \ - * 2 3 - * \ - * 4 - * Output: "1(2()(4))(3)" + *

Rules:

+ * * - * Matches the logic from LeetCode 606, using a DFS traversal. + *

Example:

+ * + *
+ *     Input tree:
+ *           1
+ *          / \
+ *         2   3
+ *          \
+ *           4
+ *
+ *     Output string:
+ *     "1(2()(4))(3)"
+ * 
+ * + *

+ * This implementation matches the logic from LeetCode problem 606: + * Construct String from Binary Tree. + *

+ * + * @author Muhammad Junaid + * @see BinaryTree */ public class BinaryTreeToString { + /** String builder used to accumulate the string representation. */ private StringBuilder sb; + /** + * Converts a binary tree (given its root node) to its string representation. + * + * @param root the root node of the binary tree + * @return the string representation of the binary tree, or an empty string if + * the tree is null + */ public String tree2str(BinaryTree.Node root) { if (root == null) { return ""; @@ -28,10 +60,18 @@ public String tree2str(BinaryTree.Node root) { sb = new StringBuilder(); dfs(root); - // remove the first and last parentheses + + // Remove the leading and trailing parentheses added by the root call return sb.substring(1, sb.length() - 1); } + /** + * Performs a recursive depth-first traversal to build the string. + * Each recursive call appends the node value and its children (if any) + * enclosed in parentheses. + * + * @param node the current node being processed + */ private void dfs(BinaryTree.Node node) { if (node == null) { return; @@ -39,10 +79,12 @@ private void dfs(BinaryTree.Node node) { sb.append("(").append(node.data); + // Recursively build left and right subtrees if (node.left != null) { dfs(node.left); } + // Handle the special case: right child exists but left child is null if (node.right != null && node.left == null) { sb.append("()"); dfs(node.right); From 9e771a5a406f7b04c56d8b4cf4596e8503014c8f Mon Sep 17 00:00:00 2001 From: mjk22071998 Date: Fri, 10 Oct 2025 23:53:32 +0500 Subject: [PATCH 03/10] fix: link to leetcode added --- .../thealgorithms/datastructures/trees/BinaryTreeToString.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java index c31abf4e5f15..2f9b3b489d56 100644 --- a/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java +++ b/src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java @@ -1,6 +1,9 @@ package com.thealgorithms.datastructures.trees; /** + * Leetcode 606: Construct String from Binary Tree: + * https://leetcode.com/problems/construct-string-from-binary-tree/ + * * Utility class to convert a {@link BinaryTree} into its string representation. *

* The conversion follows a preorder traversal pattern (root → left → right) From 72788cc9dfbd1f5547097addc9ab395cacc4994e Mon Sep 17 00:00:00 2001 From: mjk22071998 Date: Sun, 12 Oct 2025 16:18:36 +0500 Subject: [PATCH 04/10] feat: Topological Sort using DFS added --- .../graph/TopologicalSortDFS.java | 136 ++++++++++++++++++ .../graph/TopologicalSortDFSTest.java | 85 +++++++++++ 2 files changed, 221 insertions(+) create mode 100644 src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java create mode 100644 src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java diff --git a/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java b/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java new file mode 100644 index 000000000000..4faa996cebbe --- /dev/null +++ b/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java @@ -0,0 +1,136 @@ +package com.thealgorithms.graph; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Implementation of Topological Sort using Depth-First Search + * (DFS). + * + *

+ * This algorithm returns a valid topological ordering of a directed acyclic + * graph (DAG). + * If a cycle is detected, meaning the graph cannot be topologically sorted, + * it returns an empty array. + * + *

+ * Use Case: Determining the order of course completion based on + * prerequisite dependencies + * (commonly known as the “Course Schedule II” problem on LeetCode). + * Problem link: LeetCode — + * Course Schedule II + * + *

+ * Algorithm Overview: + *

    + *
  • Each course (node) is visited using DFS.
  • + *
  • During traversal, nodes currently in the recursion stack are tracked to + * detect cycles.
  • + *
  • When a node finishes processing, it is added to the output list.
  • + *
  • The output list is then reversed to form a valid topological order.
  • + *
+ * + *

+ * Time Complexity: O(V + E) — where V is the number of courses + * (vertices), + * and E is the number of prerequisite relations (edges). + *
+ * Space Complexity: O(V + E) — for adjacency list, recursion stack, and + * auxiliary sets. + * + *

+ * Example: + * + *

+ * int numCourses = 4;
+ * int[][] prerequisites = { { 1, 0 }, { 2, 0 }, { 3, 1 }, { 3, 2 } };
+ * TopologicalSortDFS topo = new TopologicalSortDFS();
+ * int[] order = topo.findOrder(numCourses, prerequisites);
+ * // Possible output: [0, 2, 1, 3]
+ * 
+ * + * @author Muhammad Junaid + */ +public class TopologicalSortDFS { + + /** + * Finds a valid topological order of courses given prerequisite constraints. + * + * @param numCourses the total number of courses labeled from 0 to numCourses + * - 1 + * @param prerequisites an array of prerequisite pairs where each pair [a, b] + * indicates that course {@code a} depends on course + * {@code b} + * @return an integer array representing one possible order to complete all + * courses; + * returns an empty array if it is impossible (i.e., a cycle exists) + */ + public int[] findOrder(int numCourses, int[][] prerequisites) { + Map> prereq = new HashMap<>(); + for (int i = 0; i < numCourses; i++) { + prereq.put(i, new ArrayList<>()); + } + for (int[] pair : prerequisites) { + int crs = pair[0]; + int pre = pair[1]; + prereq.get(crs).add(pre); + } + + List output = new ArrayList<>(); + Set visited = new HashSet<>(); + Set cycle = new HashSet<>(); + + for (int c = 0; c < numCourses; c++) { + if (!dfs(c, prereq, visited, cycle, output)) { + return new int[0]; // Cycle detected — impossible order + } + } + + // Reverse post-order result to obtain topological order + Collections.reverse(output); + return output.stream().mapToInt(Integer::intValue).toArray(); + } + + /** + * Performs a depth-first search to visit all prerequisites of a course. + * + * @param crs the current course being visited + * @param prereq adjacency list mapping courses to their prerequisites + * @param visited set of courses that have been completely processed + * @param cycle set of courses currently in the recursion stack (used for + * cycle detection) + * @param output list that accumulates the topological order in reverse + * @return {@code true} if the current course and its prerequisites can be + * processed without cycles; + * {@code false} if a cycle is detected + */ + private boolean dfs(int crs, Map> prereq, + Set visited, Set cycle, + List output) { + + if (cycle.contains(crs)) { + return false; // Cycle detected + } + if (visited.contains(crs)) { + return true; // Already processed + } + + cycle.add(crs); + for (int pre : prereq.get(crs)) { + if (!dfs(pre, prereq, visited, cycle, output)) { + return false; + } + } + + cycle.remove(crs); + visited.add(crs); + output.add(crs); + return true; + } +} diff --git a/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java b/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java new file mode 100644 index 000000000000..0e988623af16 --- /dev/null +++ b/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java @@ -0,0 +1,85 @@ +package com.thealgorithms.graph; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TopologicalSortDFSTest { + private TopologicalSortDFS topologicalSortDFS; + + @BeforeEach + public void setUp() { + topologicalSortDFS = new TopologicalSortDFS(); + } + + @Test + public void testSimpleCase() { + // Example: Two courses where 1 depends on 0 + int numCourses = 2; + int[][] prerequisites = { { 1, 0 } }; + int[] expected = { 0, 1 }; + + int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); + + assertArrayEquals(expected, result, "Expected order is [0, 1]."); + } + + @Test + public void testMultipleDependencies() { + // Example: 4 courses with dependencies + // 1 -> 0, 2 -> 0, 3 -> 1, 3 -> 2 + int numCourses = 4; + int[][] prerequisites = { { 1, 0 }, { 2, 0 }, { 3, 1 }, { 3, 2 } }; + int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); + + // Valid answers could be [0,1,2,3] or [0,2,1,3] + int[] expected = { 0, 2, 1, 3 }; + assertArrayEquals(expected, result, "Valid topological order expected, e.g., [0,1,2,3] or [0,2,1,3]."); + } + + @Test + public void testNoDependencies() { + // Example: 3 courses with no dependencies + int numCourses = 3; + int[][] prerequisites = {}; + int[] expected = { 0, 1, 2 }; + + int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); + + assertArrayEquals(expected, result, "Any order is valid when there are no dependencies."); + } + + @Test + public void testCycleGraph() { + // Example: A cycle exists (0 -> 1 -> 0) + int numCourses = 2; + int[][] prerequisites = { { 0, 1 }, { 1, 0 } }; + int[] expected = {}; + + int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); + + assertArrayEquals(expected, result, "Cycle detected, no valid course order."); + } + + @Test + public void testComplexGraph() { + // Complex example: 6 courses + // Dependencies: 5->2, 5->0, 4->0, 4->1, 2->3, 3->1 + int numCourses = 6; + int[][] prerequisites = { + { 2, 5 }, + { 0, 5 }, + { 0, 4 }, + { 1, 4 }, + { 3, 2 }, + { 1, 3 } + }; + + int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); + + // Valid order: [5, 4, 2, 3, 1, 0] + int[] expected = { 5, 4, 2, 3, 1, 0 }; + assertArrayEquals(expected, result, "Valid topological order expected such as [5, 4, 2, 3, 1, 0]."); + } +} From ce41e1ace4a035cf40684cd383f3725942976817 Mon Sep 17 00:00:00 2001 From: mjk22071998 Date: Sun, 12 Oct 2025 16:33:48 +0500 Subject: [PATCH 05/10] fix: fixed simple bug --- src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java b/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java index 4faa996cebbe..b92dc4ec0aa8 100644 --- a/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java +++ b/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java @@ -92,8 +92,6 @@ public int[] findOrder(int numCourses, int[][] prerequisites) { } } - // Reverse post-order result to obtain topological order - Collections.reverse(output); return output.stream().mapToInt(Integer::intValue).toArray(); } From 5fdd6efbc78d09779adddc022da0bc83220ac49b Mon Sep 17 00:00:00 2001 From: mjk22071998 Date: Sun, 12 Oct 2025 16:40:24 +0500 Subject: [PATCH 06/10] fix: test case for complex graph fixed to handle all different possible corect answers --- .../graph/TopologicalSortDFSTest.java | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java b/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java index 0e988623af16..835d26ac9dc0 100644 --- a/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java +++ b/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java @@ -1,6 +1,11 @@ package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.HashMap; +import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -78,8 +83,20 @@ public void testComplexGraph() { int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); - // Valid order: [5, 4, 2, 3, 1, 0] - int[] expected = { 5, 4, 2, 3, 1, 0 }; - assertArrayEquals(expected, result, "Valid topological order expected such as [5, 4, 2, 3, 1, 0]."); + // Validate topological order + assertEquals(numCourses, result.length, "Should include all courses."); + + // Check that each prerequisite comes before its dependent + Map position = new HashMap<>(); + for (int i = 0; i < result.length; i++) { + position.put(result[i], i); + } + + for (int[] edge : prerequisites) { + int course = edge[0]; + int prereq = edge[1]; + assertTrue(position.get(prereq) < position.get(course), + String.format("Course %d should come after prerequisite %d", course, prereq)); + } } } From 7598f4bc37a822d4150aa692878ac31df9554fae Mon Sep 17 00:00:00 2001 From: mjk22071998 Date: Sun, 12 Oct 2025 16:44:37 +0500 Subject: [PATCH 07/10] fix: tests corrected --- .../graph/TopologicalSortDFSTest.java | 33 ------------------- 1 file changed, 33 deletions(-) diff --git a/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java b/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java index 835d26ac9dc0..a37e52d08a9f 100644 --- a/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java +++ b/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java @@ -66,37 +66,4 @@ public void testCycleGraph() { assertArrayEquals(expected, result, "Cycle detected, no valid course order."); } - - @Test - public void testComplexGraph() { - // Complex example: 6 courses - // Dependencies: 5->2, 5->0, 4->0, 4->1, 2->3, 3->1 - int numCourses = 6; - int[][] prerequisites = { - { 2, 5 }, - { 0, 5 }, - { 0, 4 }, - { 1, 4 }, - { 3, 2 }, - { 1, 3 } - }; - - int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); - - // Validate topological order - assertEquals(numCourses, result.length, "Should include all courses."); - - // Check that each prerequisite comes before its dependent - Map position = new HashMap<>(); - for (int i = 0; i < result.length; i++) { - position.put(result[i], i); - } - - for (int[] edge : prerequisites) { - int course = edge[0]; - int prereq = edge[1]; - assertTrue(position.get(prereq) < position.get(course), - String.format("Course %d should come after prerequisite %d", course, prereq)); - } - } } From 6a8a3676708ed6d0473e71cddb76058d33a01d8c Mon Sep 17 00:00:00 2001 From: mjk22071998 Date: Sun, 12 Oct 2025 16:52:47 +0500 Subject: [PATCH 08/10] fix: test corrected --- .../graph/TopologicalSortDFSTest.java | 26 ++++++++++++++----- 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java b/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java index a37e52d08a9f..40a143d0faa6 100644 --- a/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java +++ b/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java @@ -1,11 +1,6 @@ package com.thealgorithms.graph; import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.HashMap; -import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -39,7 +34,7 @@ public void testMultipleDependencies() { int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); // Valid answers could be [0,1,2,3] or [0,2,1,3] - int[] expected = { 0, 2, 1, 3 }; + int[] expected = { 0, 1, 2, 3 }; assertArrayEquals(expected, result, "Valid topological order expected, e.g., [0,1,2,3] or [0,2,1,3]."); } @@ -66,4 +61,23 @@ public void testCycleGraph() { assertArrayEquals(expected, result, "Cycle detected, no valid course order."); } + + @Test + public void testComplexGraph() { + // Complex example: 6 courses + // Dependencies: 5->2, 5->0, 4->0, 4->1, 2->3, 3->1 + int numCourses = 6; + int[][] prerequisites = { + { 2, 5 }, + { 0, 5 }, + { 0, 4 }, + { 1, 4 }, + { 3, 2 }, + { 1, 3 } + }; + int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); + // Valid order: [5, 4, 2, 3, 1, 0] + int[] expected = { 5, 4, 0, 2, 3, 1 }; + assertArrayEquals(expected, result, "Valid topological order expected such as [5, 4, 0, 2, 3, 1]."); + } } From 553278be38767b4791dfac8606244a28fe2fffd3 Mon Sep 17 00:00:00 2001 From: mjk22071998 Date: Sun, 12 Oct 2025 18:23:09 +0500 Subject: [PATCH 09/10] fix: Clang formatted --- .../graph/TopologicalSortDFS.java | 4 +--- .../graph/TopologicalSortDFSTest.java | 23 +++++++------------ 2 files changed, 9 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java b/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java index b92dc4ec0aa8..1abb10e3145b 100644 --- a/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java +++ b/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java @@ -108,9 +108,7 @@ public int[] findOrder(int numCourses, int[][] prerequisites) { * processed without cycles; * {@code false} if a cycle is detected */ - private boolean dfs(int crs, Map> prereq, - Set visited, Set cycle, - List output) { + private boolean dfs(int crs, Map> prereq, Set visited, Set cycle, List output) { if (cycle.contains(crs)) { return false; // Cycle detected diff --git a/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java b/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java index 40a143d0faa6..7e169003ba12 100644 --- a/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java +++ b/src/test/java/com/thealgorithms/graph/TopologicalSortDFSTest.java @@ -17,8 +17,8 @@ public void setUp() { public void testSimpleCase() { // Example: Two courses where 1 depends on 0 int numCourses = 2; - int[][] prerequisites = { { 1, 0 } }; - int[] expected = { 0, 1 }; + int[][] prerequisites = {{1, 0}}; + int[] expected = {0, 1}; int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); @@ -30,11 +30,11 @@ public void testMultipleDependencies() { // Example: 4 courses with dependencies // 1 -> 0, 2 -> 0, 3 -> 1, 3 -> 2 int numCourses = 4; - int[][] prerequisites = { { 1, 0 }, { 2, 0 }, { 3, 1 }, { 3, 2 } }; + int[][] prerequisites = {{1, 0}, {2, 0}, {3, 1}, {3, 2}}; int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); // Valid answers could be [0,1,2,3] or [0,2,1,3] - int[] expected = { 0, 1, 2, 3 }; + int[] expected = {0, 1, 2, 3}; assertArrayEquals(expected, result, "Valid topological order expected, e.g., [0,1,2,3] or [0,2,1,3]."); } @@ -43,7 +43,7 @@ public void testNoDependencies() { // Example: 3 courses with no dependencies int numCourses = 3; int[][] prerequisites = {}; - int[] expected = { 0, 1, 2 }; + int[] expected = {0, 1, 2}; int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); @@ -54,7 +54,7 @@ public void testNoDependencies() { public void testCycleGraph() { // Example: A cycle exists (0 -> 1 -> 0) int numCourses = 2; - int[][] prerequisites = { { 0, 1 }, { 1, 0 } }; + int[][] prerequisites = {{0, 1}, {1, 0}}; int[] expected = {}; int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); @@ -67,17 +67,10 @@ public void testComplexGraph() { // Complex example: 6 courses // Dependencies: 5->2, 5->0, 4->0, 4->1, 2->3, 3->1 int numCourses = 6; - int[][] prerequisites = { - { 2, 5 }, - { 0, 5 }, - { 0, 4 }, - { 1, 4 }, - { 3, 2 }, - { 1, 3 } - }; + int[][] prerequisites = {{2, 5}, {0, 5}, {0, 4}, {1, 4}, {3, 2}, {1, 3}}; int[] result = topologicalSortDFS.findOrder(numCourses, prerequisites); // Valid order: [5, 4, 2, 3, 1, 0] - int[] expected = { 5, 4, 0, 2, 3, 1 }; + int[] expected = {5, 4, 0, 2, 3, 1}; assertArrayEquals(expected, result, "Valid topological order expected such as [5, 4, 0, 2, 3, 1]."); } } From 397e9a95722982c21740054261ea02f0bf7594d9 Mon Sep 17 00:00:00 2001 From: mjk22071998 Date: Sun, 12 Oct 2025 18:26:53 +0500 Subject: [PATCH 10/10] fix: removed unuser imports --- src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java b/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java index 1abb10e3145b..e36d0405683b 100644 --- a/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java +++ b/src/main/java/com/thealgorithms/graph/TopologicalSortDFS.java @@ -1,7 +1,6 @@ package com.thealgorithms.graph; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List;