Skip to content

Commit d4aeb8c

Browse files
author
Mauricio Klein
committed
Add solution for challenge #44
1 parent 18344dc commit d4aeb8c

File tree

6 files changed

+69
-0
lines changed

6 files changed

+69
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,4 @@
4343
- [x] [Challenge 41: Maximum sequence of consecutive numbers](challenge-41/)
4444
- [x] [Challenge 42: Depth of a stringified binary tree](challenge-42/)
4545
- [x] [Challenge 43: Contiguous Subarray with Maximum Sum](challenge-43/)
46+
- [x] [Challenge 44: Find the k-th Largest Element in a List](challenge-44/)

challenge-44/Makefile

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
test:
2+
python test_*.py
3+
4+
.PHONY: test

challenge-44/README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Find the k-th Largest Element in a List
2+
3+
This problem was asked by Facebook.
4+
5+
## Description
6+
7+
Given a list, find the k-th largest element in the list.
8+
9+
## Example
10+
```
11+
Input:
12+
list = [3, 5, 2, 4, 6, 8]
13+
k = 3
14+
15+
Output: 5
16+
```

challenge-44/__init__.py

Whitespace-only changes.

challenge-44/solver.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import random
2+
3+
def k_largest(nums, k):
4+
N = len(nums)
5+
6+
k_index = N - k
7+
quick_select(nums, k_index, 0, N-1)
8+
9+
return nums[k_index]
10+
11+
def quick_select(nums, k, left, right):
12+
if left == right:
13+
return
14+
15+
wall, pivot = left, ((right + left) // 2)
16+
17+
# Move pivot to the end of the list
18+
swap(nums, right, pivot)
19+
pivot = right
20+
21+
for i in range(left, right):
22+
if nums[i] < nums[pivot]:
23+
swap(nums, i, wall)
24+
wall += 1
25+
26+
# Put pivot in the right place
27+
swap(nums, wall, pivot)
28+
pivot = wall
29+
30+
if k < pivot:
31+
quick_select(nums, k, left, pivot - 1)
32+
elif k > pivot:
33+
quick_select(nums, k, pivot + 1, right)
34+
35+
def swap(arr, i, j):
36+
arr[i], arr[j] = arr[j], arr[i]

challenge-44/test_solver.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import unittest
2+
import random
3+
from solver import k_largest
4+
5+
class TestSolver(unittest.TestCase):
6+
def test_k_largest(self):
7+
self.assertEqual(k_largest([3, 5, 2, 4, 6, 8], k=3), 5)
8+
self.assertEqual(k_largest([3, 5, 2, 4, 6, 8], k=1), 8)
9+
self.assertEqual(k_largest([3 ], k=1), 3)
10+
11+
if __name__ == "__main__":
12+
unittest.main()

0 commit comments

Comments
 (0)