-
Notifications
You must be signed in to change notification settings - Fork 2
feat(algorithms, heaps): top k and kth largest #152
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
608e7b1
feat(algorithms, heaps): top k and kth largest
BrianLusina 0f36bfc
updating DIRECTORY.md
9a3ea30
feat(algorithms, heaps): top k closest point to origin
BrianLusina 2bb4e1f
updating DIRECTORY.md
5af34d3
Update algorithms/heap/topklargest/__init__.py
BrianLusina bb4ced1
Update algorithms/heap/topklargest/__init__.py
BrianLusina 8bbd95b
Update algorithms/heap/topkclosesttoorigin/__init__.py
BrianLusina 90c4681
Update algorithms/heap/topkclosesttoorigin/test_top_k_closest_to_orig…
BrianLusina 6ca89ad
refactor(algorithms, heaps): move from puzzles package
BrianLusina 2db74fa
feat(algorithms, matrix, dfs): is valid sudoku matrix puzzle and dfs …
BrianLusina 7256932
refactor(algorithms, heaps): move to heap package
BrianLusina 98018a8
updating DIRECTORY.md
39a67e0
Update algorithms/matrix/isvalidsudoku/__init__.py
BrianLusina File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
2 changes: 1 addition & 1 deletion
2
...happy_string/test_longest_happy_string.py → ...happy_string/test_longest_happy_string.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| # K Closest Points to Origin | ||
|
|
||
| Given a list of points in the form [[x1, y1], [x2, y2], ... [xn, yn]] and an integer k, find the k closest points to the | ||
| origin (0, 0) on the 2D plane. | ||
|
|
||
| The distance between two points (x, y) and (a, b) is calculated using the formula: | ||
|
|
||
| √(x1 - a2)2 + (y1 - b2)2 | ||
|
|
||
| Return the k closest points in any order. | ||
|
|
||
| ## Examples | ||
|
|
||
| ```text | ||
| Input: | ||
|
|
||
| points = [[3,4],[2,2],[1,1],[0,0],[5,5]] | ||
| k = 3 | ||
|
|
||
| Output: | ||
| [[2,2],[1,1],[0,0]] | ||
|
|
||
| Also Valid: | ||
|
|
||
| [[2,2],[0,0],[1,1]] | ||
| [[1,1],[0,0],[2,2]] | ||
| [[1,1],[2,2],[0,0]] | ||
| ... | ||
| [[0,0],[1,1],[2,2]] | ||
| ``` | ||
|
|
||
|  | ||
|
|
||
| ```text | ||
| Input: points = [[3,3],[5,-1],[-2,4]], k = 2 | ||
| Output: [[3,3],[-2,4]] | ||
| Explanation: The answer [[-2,4],[3,3]] would also be accepted. | ||
| ``` | ||
|
|
||
| ```text | ||
| Input: points = [[1,3],[-2,2]], k = 1 | ||
| Output: [[-2,2]] | ||
|
|
||
| Explanation: | ||
| The distance between (1, 3) and the origin is sqrt(10). | ||
| The distance between (-2, 2) and the origin is sqrt(8). | ||
| Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. | ||
| We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. | ||
| ``` | ||
|
|
||
| ## Solution | ||
|
|
||
| - [Approach 1](#approach-1-sorting) | ||
| - [Approach 2](#approach-2-max-heap) | ||
|
|
||
| ### Approach 1: Sorting | ||
|
|
||
| The simplest approach is to sort calculate the distance of each point from the origin and sort the points based on their | ||
| distance. This approach has a time complexity of O(n log n) where n is the number of points in the array, and a space | ||
| complexity of O(n) (to store the sorted array of distances). | ||
|
|
||
| ### Approach 2: Max Heap | ||
|
|
||
| This problem can be solved using a similar approach to the one used to solve [Kth Largest Element in an Array](../topklargest/README.md). The key | ||
| difference is that we need to store the k closest points to the origin, rather than the k largest elements. Since we are | ||
| looking for the k smallest elements, we need a max-heap, rather than a min-heap. | ||
|
|
||
| By default, python's heapq module implements a min-heap, but we can make it behave like a max-heap by negating the values | ||
| of everything we push onto it. | ||
|
|
||
| We add the first k points to the heap by pushing a tuple containing the negative of the distance from the origin, and the | ||
| index of the point. After that is finished, our heap contains the k closest points to the origin that we've seen so far, | ||
| with the point furthest from the origin at the root of the heap. | ||
|
|
||
| For each point after the first k, we calculate the distance from the origin and compare it with the root of the heap. If | ||
| the current point is closer to the origin than the root of the heap, we pop the root and push the current point into the | ||
| heap. This way, the heap will always contain the k closest points to the origin we've seen so far. | ||
|
|
||
| At the end of the iteration, the heap will contain the k closest points to the origin. We can iterate over each point in | ||
| the heap and return the point associated with each tuple. | ||
|
|
||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|  | ||
|
|
||
| #### Complexity Analysis | ||
|
|
||
| ##### Time Complexity: O(n log k) | ||
|
|
||
| Where n is the number of points in the array and k is the input parameter. We iterate over | ||
| all points, and in the worst case, we both push and pop each point from the heap, which takes O(log k) time per point. | ||
|
|
||
| ##### Space Complexity: O(k) | ||
|
|
||
| Where k is the input parameter. The space is used by the heap to store the k closest points to the origin. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| from typing import List, Tuple | ||
| import heapq | ||
|
|
||
|
|
||
| def k_closest_to_origin(points: List[List[int]], k: int) -> List[List[int]]: | ||
| # Max heap will store the top k points closest to the origin in the form (-distance, idx). The distance is negated | ||
| # because in Python, the heapq module uses min-heap by default. Negating values gives us a maximum heap. | ||
| # We store the idx of the point for later retrieval from the points array passed in | ||
| max_heap: List[Tuple[int, int]] = [] | ||
|
|
||
| for idx, point in enumerate(points): | ||
| x, y = point | ||
| # calculate the distance for this point from the origin | ||
| distance = x * x + y * y | ||
|
|
||
| # If the contents of the heap are less than the desired top k, then we add the current point's distance and idx | ||
| if len(max_heap) < k: | ||
| heapq.heappush(max_heap, (-distance, idx)) | ||
| # We check if the calculated distance of this point is less than the top element in the heap. If this point | ||
| # is closer to the origin that what is at the root of the heap, we pop the root of the heap and add this | ||
| # new distance and index. | ||
| # Note the negation here again to get the actual distance | ||
| elif distance < -max_heap[0][0]: | ||
| heapq.heappushpop(max_heap, (-distance, idx)) | ||
|
|
||
| # Return the top k points closest to origin. We use 1 to get the index of the point from the original points list | ||
| # as that is what is stored in the max heap | ||
| return [points[point[1]] for point in max_heap] | ||
|
|
||
|
|
||
| def k_closest_to_origin_sorting(points: List[List[int]], k: int) -> List[List[int]]: | ||
| # Sort the points by the distance from the origin. This incurs a cost of O(n log(n)) and space cost of O(n) due to | ||
| # timsort | ||
| sorted_points = sorted(points, key=lambda p: p[0] ** 2 + p[1] ** 2) | ||
| # Retrieve the top k points closest to the origin | ||
| return sorted_points[:k] |
Binary file added
BIN
+41.3 KB
.../heap/topkclosesttoorigin/images/examples/top_k_closest_to_origin_example_1.png
Oops, something went wrong.
Binary file added
BIN
+34.6 KB
...eap/topkclosesttoorigin/images/solutions/top_k_closest_to_origin_solution_0.png
Oops, something went wrong.
Binary file added
BIN
+31.5 KB
...eap/topkclosesttoorigin/images/solutions/top_k_closest_to_origin_solution_1.png
Oops, something went wrong.
Binary file added
BIN
+55.2 KB
...ap/topkclosesttoorigin/images/solutions/top_k_closest_to_origin_solution_10.png
Oops, something went wrong.
Binary file added
BIN
+30.2 KB
...ap/topkclosesttoorigin/images/solutions/top_k_closest_to_origin_solution_11.png
Oops, something went wrong.
Binary file added
BIN
+36.1 KB
...eap/topkclosesttoorigin/images/solutions/top_k_closest_to_origin_solution_2.png
Oops, something went wrong.
Binary file added
BIN
+49.8 KB
...eap/topkclosesttoorigin/images/solutions/top_k_closest_to_origin_solution_3.png
Oops, something went wrong.
Binary file added
BIN
+45.1 KB
...eap/topkclosesttoorigin/images/solutions/top_k_closest_to_origin_solution_4.png
Oops, something went wrong.
Binary file added
BIN
+54.9 KB
...eap/topkclosesttoorigin/images/solutions/top_k_closest_to_origin_solution_5.png
Oops, something went wrong.
Binary file added
BIN
+52.3 KB
...eap/topkclosesttoorigin/images/solutions/top_k_closest_to_origin_solution_6.png
Oops, something went wrong.
Binary file added
BIN
+55 KB
...eap/topkclosesttoorigin/images/solutions/top_k_closest_to_origin_solution_7.png
Oops, something went wrong.
Binary file added
BIN
+54.3 KB
...eap/topkclosesttoorigin/images/solutions/top_k_closest_to_origin_solution_8.png
Oops, something went wrong.
Binary file added
BIN
+56.5 KB
...eap/topkclosesttoorigin/images/solutions/top_k_closest_to_origin_solution_9.png
Oops, something went wrong.
39 changes: 39 additions & 0 deletions
39
algorithms/heap/topkclosesttoorigin/test_top_k_closest_to_origin.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import unittest | ||
| from typing import List | ||
| from parameterized import parameterized | ||
| from algorithms.heap.topkclosesttoorigin import ( | ||
| k_closest_to_origin, | ||
| k_closest_to_origin_sorting, | ||
| ) | ||
|
|
||
| TOP_K_CLOSEST_TO_ORIGIN = [ | ||
| ([[3, 4], [2, 2], [1, 1], [0, 0], [5, 5]], 3, [[2, 2], [1, 1], [0, 0]]), | ||
| ([[1, 3], [-2, 2]], 1, [[-2, 2]]), | ||
| ([[3, 3], [5, -1], [-2, 4]], 2, [[3, 3], [-2, 4]]), | ||
| ] | ||
|
|
||
|
|
||
| class TopKClosestToOriginTestCase(unittest.TestCase): | ||
| @parameterized.expand(TOP_K_CLOSEST_TO_ORIGIN) | ||
| def test_top_k_closest_to_origin( | ||
| self, points: List[List[int]], k: int, expected: List[List[int]] | ||
| ): | ||
| actual = k_closest_to_origin(points, k) | ||
|
|
||
| sorted_expected = sorted(expected, key=lambda x: (x[0], x[1])) | ||
| sorted_actual = sorted(actual, key=lambda x: (x[0], x[1])) | ||
| self.assertEqual(sorted_expected, sorted_actual) | ||
|
|
||
| @parameterized.expand(TOP_K_CLOSEST_TO_ORIGIN) | ||
| def test_top_k_closest_to_origin_sorting( | ||
| self, points: List[List[int]], k: int, expected: List[List[int]] | ||
| ): | ||
| actual = k_closest_to_origin_sorting(points, k) | ||
|
|
||
| sorted_expected = sorted(expected, key=lambda x: x[0]) | ||
| sorted_actual = sorted(actual, key=lambda x: x[0]) | ||
| self.assertEqual(sorted_expected, sorted_actual) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
File renamed without changes.
File renamed without changes.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.