Skip to content

feat(algorithms, k-way-merge): kth smallest element in sorted matrix#192

Merged
BrianLusina merged 2 commits intomainfrom
feat/algorithms-k-way-merge
Mar 25, 2026
Merged

feat(algorithms, k-way-merge): kth smallest element in sorted matrix#192
BrianLusina merged 2 commits intomainfrom
feat/algorithms-k-way-merge

Conversation

@BrianLusina
Copy link
Copy Markdown
Owner

@BrianLusina BrianLusina commented Mar 25, 2026

Describe your change:

Shows algorithms in the K-Way Merge Pattern to solve the problem of finding the kth smallest element in a sorted matrix.

  • 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

Release Notes

  • New Features

    • Added K-Way Merge algorithm implementation for finding the kth smallest element in a sorted matrix, featuring two heap-based approaches.
  • Documentation

    • Added comprehensive README with problem description, algorithm approach, constraints, and complexity analysis.
  • Tests

    • Added parametrised unit tests covering various matrix sizes and value patterns.

@BrianLusina BrianLusina self-assigned this Mar 25, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 25, 2026

📝 Walkthrough

Walkthrough

New k-way merge algorithm added for computing the kth smallest element in a sorted matrix using heap-based approaches. Includes two implementations, comprehensive documentation, parameterised test coverage, and a minor docstring correction in an existing utility function.

Changes

Cohort / File(s) Summary
New K-Way Merge Algorithm
algorithms/k_way_merge/kth_smallest_element_in_matrix/__init__.py
Two heap-based implementations: kth_smallest_in_matrix_with_heap_1 (pushes all elements, pops k-1 times) and kth_smallest_in_matrix_with_heap_2 (seeded heap with first row elements, optimised for sparse matrices). Both use heapq for min-heap operations.
Algorithm Documentation & Catalogue
algorithms/k_way_merge/kth_smallest_element_in_matrix/README.md, DIRECTORY.md
Added detailed problem statement, algorithm approach explanation, complexity analysis, example cases, and constraint specifications. Catalogue entry registered linking to test file.
Test Suite
algorithms/k_way_merge/kth_smallest_element_in_matrix/test_kth_smallest_element_in_matrix.py
Parameterised unit tests covering both implementations with cases including single-element matrices, negative values, duplicates, and 5×5 matrices.
Existing Documentation Fix
datastructures/trees/binary/search_tree/bst_utils.py
Minor docstring formatting adjustment in kth_smallest_element function (spacing correction only).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

Trees

Poem

🐰 A matrix of numbers, so sorted and neat,
With heaps we shall merge, the kth we shall greet,
Two paths through the rows, optimised and bright,
The smallest shall surface, in algorithmic light! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main addition: a K-way merge algorithm for finding the kth smallest element in a sorted matrix, which is exactly what the changeset implements.
Description check ✅ Passed The description is mostly complete with all required sections and checklist items addressed. All applicable checklist items are checked, indicating the author followed guidelines for algorithm contributions including type hints, doctests, and URLs.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/algorithms-k-way-merge

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
Copy Markdown
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: 4

🧹 Nitpick comments (1)
algorithms/k_way_merge/kth_smallest_element_in_matrix/test_kth_smallest_element_in_matrix.py (1)

33-42: Rename matrx to matrix for readability.

Line 34 and Line 41 use a misspelt parameter name. It works, but correcting it improves clarity when scanning tests.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@algorithms/k_way_merge/kth_smallest_element_in_matrix/test_kth_smallest_element_in_matrix.py`
around lines 33 - 42, Rename the misspelled parameter `matrx` to `matrix` in the
test functions so names are clear: update the function signatures for
test_kth_smallest_in_matrix_1 and test_kth_smallest_in_matrix_2 to accept
`matrix: List[List[int]]` (instead of `matrx`) and replace all uses inside those
functions (e.g., the call to kth_smallest_in_matrix_with_heap_1(matrx, k)) to
use `matrix`, ensuring parameterized.expand still supplies the same arguments.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@algorithms/k_way_merge/kth_smallest_element_in_matrix/__init__.py`:
- Around line 6-13: Add one executable doctest to each public function's
docstring (e.g., kth_smallest_element_in_matrix and the other public function
referenced at lines 33-40): include a small example matrix, a k value, and the
expected integer result using the Python doctest format (">>> func(matrix, k)"
followed by the result on the next line). Insert the doctest inside the existing
triple-quoted docstring before the closing quotes, keep it concise (one example
per function), and ensure the example uses the exact function name as defined so
tests can run.
- Around line 5-72: Add shared input validation at the start of both
kth_smallest_in_matrix_with_heap_1 and kth_smallest_in_matrix_with_heap_2:
verify matrix is not empty, all rows are non-empty (or treat total_elements =
sum(len(row) for row in matrix) > 0), k is a positive integer, and k <=
total_elements; if any check fails raise ValueError with a clear message. In
kth_smallest_in_matrix_with_heap_1 validate before building min_heap so we never
index out of range, and in kth_smallest_in_matrix_with_heap_2 validate before
using row_count/min_numbers (this prevents returning the default 0 when
min_numbers is empty); use the existing symbols matrix, k, row_count,
min_heap/min_numbers to locate where to add the checks.

In `@algorithms/k_way_merge/kth_smallest_element_in_matrix/README.md`:
- Around line 90-92: The README's space complexity line overstates memory:
update the "Space Complexity" section of kth_smallest_element_in_matrix to state
that the min-heap uses O(min(row_count, k)) space (or O(min(m, k))) rather than
O(n), and clarify briefly that the heap holds at most one entry per row (up to k
entries) in the heap-based approach (min-heap).

In `@datastructures/trees/binary/search_tree/bst_utils.py`:
- Line 35: In the bst_utils.py docstring there is a double space before "Kth"
("Finds the  Kth smallest element in a binary search tree."); update that string
to a single space ("Finds the Kth smallest element in a binary search tree.") —
locate the docstring containing that exact sentence (e.g., in the function or
module that declares the BST utility like find_kth_smallest or similar) and
normalize the spacing so the documentation reads with a single space.

---

Nitpick comments:
In
`@algorithms/k_way_merge/kth_smallest_element_in_matrix/test_kth_smallest_element_in_matrix.py`:
- Around line 33-42: Rename the misspelled parameter `matrx` to `matrix` in the
test functions so names are clear: update the function signatures for
test_kth_smallest_in_matrix_1 and test_kth_smallest_in_matrix_2 to accept
`matrix: List[List[int]]` (instead of `matrx`) and replace all uses inside those
functions (e.g., the call to kth_smallest_in_matrix_with_heap_1(matrx, k)) to
use `matrix`, ensuring parameterized.expand still supplies the same arguments.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 68068257-b8ab-4584-a67c-3393ade4b9f6

📥 Commits

Reviewing files that changed from the base of the PR and between 7044acc and b9a90fe.

⛔ Files ignored due to path filters (11)
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/images/examples/kth_smallest_element_in_matrix_example_1.png is excluded by !**/*.png
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/images/examples/kth_smallest_element_in_matrix_example_2.png is excluded by !**/*.png
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/images/examples/kth_smallest_element_in_matrix_example_3.png is excluded by !**/*.png
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/images/solutions/kth_smallest_element_in_matrix_solution_1.png is excluded by !**/*.png
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/images/solutions/kth_smallest_element_in_matrix_solution_2.png is excluded by !**/*.png
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/images/solutions/kth_smallest_element_in_matrix_solution_3.png is excluded by !**/*.png
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/images/solutions/kth_smallest_element_in_matrix_solution_4.png is excluded by !**/*.png
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/images/solutions/kth_smallest_element_in_matrix_solution_5.png is excluded by !**/*.png
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/images/solutions/kth_smallest_element_in_matrix_solution_6.png is excluded by !**/*.png
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/images/solutions/kth_smallest_element_in_matrix_solution_7.png is excluded by !**/*.png
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/images/solutions/kth_smallest_element_in_matrix_solution_8.png is excluded by !**/*.png
📒 Files selected for processing (6)
  • DIRECTORY.md
  • algorithms/k_way_merge/__init__.py
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/README.md
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/__init__.py
  • algorithms/k_way_merge/kth_smallest_element_in_matrix/test_kth_smallest_element_in_matrix.py
  • datastructures/trees/binary/search_tree/bst_utils.py

@BrianLusina BrianLusina enabled auto-merge March 25, 2026 08:37
@BrianLusina BrianLusina disabled auto-merge March 25, 2026 08:37
@BrianLusina BrianLusina merged commit 13e626e into main Mar 25, 2026
5 of 6 checks passed
@BrianLusina BrianLusina deleted the feat/algorithms-k-way-merge branch March 25, 2026 08:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant