Skip to content

Conversation

@BrianLusina
Copy link
Owner

@BrianLusina BrianLusina commented Jan 1, 2026

Describe your change:

Refactor reorder routes algorithm, adding an alternative solution

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Documentation change?

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
  • If this pull request resolves one or more open issues then the commit message contains Fixes: #{$ISSUE_NO}.

Summary by CodeRabbit

  • Documentation

    • Enhanced README with comprehensive DFS-based solution explanation and updated image paths.
  • New Features

    • Added two function-based implementations for solving the Reorder Routes problem.
  • Tests

    • Refactored test suite with parameterized testing approach for improved coverage.

✏️ Tip: You can customize this high-level summary in your review settings.

@BrianLusina BrianLusina self-assigned this Jan 1, 2026
@BrianLusina BrianLusina added enhancement Algorithm Algorithm Problem Datastructures Datastructures Documentation Documentation Updates Graph Graph data structures and algorithms Array Array data structure Depth First Search labels Jan 1, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 1, 2026

📝 Walkthrough

Walkthrough

The changes refactor the Reorder Routes graph algorithm by replacing a class-based Solution structure with two module-level DFS functions (min_reorder and min_reorder_2), modernize test coverage via parameterized testing, and expand documentation with comprehensive algorithm explanation and updated example paths.

Changes

Cohort / File(s) Summary
Documentation
algorithms/graphs/reorder_routes/README.md
Updated example image paths and added comprehensive DFS-based solution explanation including step-by-step approach, DFS definition, and time/space complexity analysis.
Implementation Refactor
algorithms/graphs/reorder_routes/__init__.py
Removed Solution class and replaced with two module-level functions: min_reorder() using directional signs (1 for original direction, 0 for reversal) in adjacency map, and min_reorder_2() using visited set approach. Both maintain O(n) time/space via DFS from node 0.
Test Restructuring
algorithms/graphs/reorder_routes/test_reorder_routes.py
Converted individual hard-coded test methods into parameterized test suite with REORDER_ROUTES_TEST_CASES constant, updated imports for parameterized framework, and unified test execution via single test_min_reorder_routes() method.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 A graph reordered, two paths now shine,
DFS flows through nodes, directional signs align,
Tests parameterized, documentation refined,
From class to function, refactored by design!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor(algorithms, graphs): reorder routes' directly summarizes the main change - refactoring the reorder routes algorithm in the graphs module with improved implementations and documentation.
Description check ✅ Passed The description follows the template structure, clearly states the change is a refactor with an alternative solution, marks all applicable checklist items, and all required sections are present and completed except for an issue resolution reference which is optional.
✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (6)
algorithms/graphs/reorder_routes/README.md (2)

18-18: Add alt text to images for accessibility.

The static analysis tool correctly flags that these images lack alternate text. Adding descriptive alt text improves accessibility for screen readers and provides context when images fail to load.

🔎 Suggested fix
-![](images/examples/reorder_routes_example_1.png)
+![Example 1: Graph with 6 nodes showing roads to reorient](images/examples/reorder_routes_example_1.png)
-![](images/examples/reorder_routes_example_2.png)
+![Example 2: Graph with 5 nodes showing roads to reorient](images/examples/reorder_routes_example_2.png)

Also applies to: 26-26


55-55: Consider using a proper heading instead of bold emphasis.

For better document structure and navigation, use a heading tag (e.g., ###) rather than bold text for section titles.

🔎 Suggested fix
-**Define the DFS function**
+### Define the DFS function
algorithms/graphs/reorder_routes/test_reorder_routes.py (1)

17-23: Consider adding test coverage for min_reorder_2.

The alternative implementation min_reorder_2 introduced in __init__.py is not covered by tests. Since both functions solve the same problem, you could reuse the same test cases.

🔎 Suggested addition
from algorithms.graphs.reorder_routes import min_reorder, min_reorder_2

# ... existing test class ...

class ReorderRoutes2TestCase(unittest.TestCase):
    @parameterized.expand(REORDER_ROUTES_TEST_CASES)
    def test_min_reorder_2_routes(
        self, n: int, connections: List[List[int]], expected: int
    ):
        actual = min_reorder_2(n, connections)
        self.assertEqual(expected, actual)
algorithms/graphs/reorder_routes/__init__.py (3)

36-36: Prefer defaultdict(list) over defaultdict(lambda: []).

Using list directly as the factory is more idiomatic and slightly more efficient.

🔎 Suggested fix
-    adj: Dict[int, List[List[int]]] = defaultdict(lambda: [])
+    adj: Dict[int, List[List[int]]] = defaultdict(list)

9-9: Minor docstring fixes needed.

  • Line 9: Typo Complexity; should be Complexity:
  • Line 22: Extra leading space
  • Line 26: The parameter is an edge list, not an "adjacency matrix"
🔎 Suggested fix
-    Complexity;
+    Complexity:
-         It would take up O(n) space in that case.
+        It would take up O(n) space in that case.
-        connections(list): adjacency matrix for a directed graph or in this case, representation of cities
+        connections(list): edge list for a directed graph or in this case, representation of city roads

Also applies to: 22-22, 26-26


69-86: Add docstring to min_reorder_2 for consistency.

The function lacks documentation. Since this is an alternative implementation of the same algorithm, consider adding a brief docstring explaining the approach and any differences from min_reorder.

🔎 Suggested docstring
 def min_reorder_2(n: int, connections: List[List[int]]) -> int:
+    """Alternative DFS-based solution using a visited set instead of parent tracking.
+    
+    Args:
+        n: Number of cities (vertices)
+        connections: List of directed edges [from_city, to_city]
+    
+    Returns:
+        Minimum number of edges to reverse so all cities can reach city 0
+    """
     def dfs(city, graph, visited):
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d9861d8 and 2e825f6.

⛔ Files ignored due to path filters (11)
  • algorithms/graphs/reorder_routes/images/examples/reorder_routes_example_1.png is excluded by !**/*.png
  • algorithms/graphs/reorder_routes/images/examples/reorder_routes_example_2.png is excluded by !**/*.png
  • algorithms/graphs/reorder_routes/images/solutions/reorder_routes_solution_1.png is excluded by !**/*.png
  • algorithms/graphs/reorder_routes/images/solutions/reorder_routes_solution_2.png is excluded by !**/*.png
  • algorithms/graphs/reorder_routes/images/solutions/reorder_routes_solution_3.png is excluded by !**/*.png
  • algorithms/graphs/reorder_routes/images/solutions/reorder_routes_solution_4.png is excluded by !**/*.png
  • algorithms/graphs/reorder_routes/images/solutions/reorder_routes_solution_5.png is excluded by !**/*.png
  • algorithms/graphs/reorder_routes/images/solutions/reorder_routes_solution_6.png is excluded by !**/*.png
  • algorithms/graphs/reorder_routes/images/solutions/reorder_routes_solution_7.png is excluded by !**/*.png
  • algorithms/graphs/reorder_routes/images/solutions/reorder_routes_solution_8.png is excluded by !**/*.png
  • algorithms/graphs/reorder_routes/images/solutions/reorder_routes_solution_9.png is excluded by !**/*.png
📒 Files selected for processing (3)
  • algorithms/graphs/reorder_routes/README.md
  • algorithms/graphs/reorder_routes/__init__.py
  • algorithms/graphs/reorder_routes/test_reorder_routes.py
🧰 Additional context used
🧬 Code graph analysis (1)
algorithms/graphs/reorder_routes/test_reorder_routes.py (1)
algorithms/graphs/reorder_routes/__init__.py (1)
  • min_reorder (5-66)
🪛 markdownlint-cli2 (0.18.1)
algorithms/graphs/reorder_routes/README.md

18-18: Images should have alternate text (alt text)

(MD045, no-alt-text)


26-26: Images should have alternate text (alt text)

(MD045, no-alt-text)


55-55: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

🔇 Additional comments (2)
algorithms/graphs/reorder_routes/test_reorder_routes.py (1)

6-14: Good test coverage with parameterized approach.

The test cases cover various scenarios including edge cases like all roads already pointing toward city 0 (expected=0) and a straight chain (expected=3).

algorithms/graphs/reorder_routes/__init__.py (1)

41-57: Algorithm implementation is correct.

The DFS traversal correctly uses parent tracking to avoid revisiting nodes and accumulates the reorder count based on edge direction signs. The logic properly handles the tree structure.

@BrianLusina BrianLusina merged commit 7f2ad34 into main Jan 1, 2026
6 of 8 checks passed
@BrianLusina BrianLusina deleted the feat/algorithms-graphs-reorder-routes branch January 1, 2026 07:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Algorithm Algorithm Problem Array Array data structure Datastructures Datastructures Depth First Search Documentation Documentation Updates enhancement Graph Graph data structures and algorithms

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants