Skip to content

Commit 2be2a06

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 4, 33, 34, 153 and 162
1 parent 4f2c13c commit 2be2a06

11 files changed

+300
-1
lines changed

README.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
<img src="https://img.shields.io/badge/tests-passed-brightgreen">
1616
</a>
1717
<a>
18-
<img src="https://img.shields.io/badge/coverage-98%25-brightgreen">
18+
<img src="https://img.shields.io/badge/coverage-97%25-brightgreen">
1919
</a>
2020
</h1>
2121
</div>
@@ -27,6 +27,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
2727
- [1 Two Sum](https://leetcode.com/problems/two-sum/description/)
2828
- [2 Add Two Numbers](https://leetcode.com/problems/add-two-numbers/description/)
2929
- [3 Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/description/)
30+
- [4 Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/description/)
3031
- [6 Zigzag Conversion](https://leetcode.com/problems/zigzag-conversion/description/)
3132
- [9 Palindrome Number](https://leetcode.com/problems/palindrome-number/description/)
3233
- [11 Container With Most Water](https://leetcode.com/problems/container-with-most-water/description/)
@@ -45,6 +46,8 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
4546
- [27 Remove Element](https://leetcode.com/problems/remove-element/description/)
4647
- [28 Find the Index of the First Occurrence in a String](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/)
4748
- [30 Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/)
49+
- [33 Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/description/)
50+
- [34 Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/)
4851
- [35 Search Insert Position](https://leetcode.com/problems/search-insert-position/description/)
4952
- [36 Valid Sudoku](https://leetcode.com/problems/valid-sudoku/description/)
5053
- [39 Combination Sum](https://leetcode.com/problems/combination-sum/description/)
@@ -110,7 +113,9 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
110113
- [149 Max Points on a Line](https://leetcode.com/problems/max-points-on-a-line/description/)
111114
- [150 Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/description/)
112115
- [151 Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/description/)
116+
- [153 Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/)
113117
- [155 Min Stack](https://leetcode.com/problems/min-stack/description/)
118+
- [162 Find Peak Element](https://leetcode.com/problems/find-peak-element/description/)
114119
- [167 Two Sum II - Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/description/)
115120
- [169 Majority Element](https://leetcode.com/problems/majority-element/description/)
116121
- [172 Factorial Trailing Zeroes](https://leetcode.com/problems/factorial-trailing-zeroes/description/)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def findMin(self, nums: List[int]) -> int:
8+
"""
9+
Suppose an array of length n sorted in ascending order is rotated between 1 and
10+
n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
11+
- [4,5,6,7,0,1,2] if it was rotated 4 times.
12+
- [0,1,2,4,5,6,7] if it was rotated 7 times.
13+
14+
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in
15+
the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
16+
17+
Given the sorted rotated array nums of unique elements, return the minimum
18+
element of this array.
19+
20+
You must write an algorithm that runs in O(log n) time.
21+
"""
22+
left, right = 0, len(nums) - 1
23+
minVal = float("inf")
24+
25+
while left <= right:
26+
if nums[left] < nums[right]:
27+
# sorted portion
28+
if nums[left] < minVal:
29+
minVal = nums[left]
30+
break
31+
mid = (left + right) // 2
32+
if nums[mid] < minVal:
33+
minVal = nums[mid]
34+
if nums[left] <= nums[mid]:
35+
# left sorted portion
36+
left = mid + 1
37+
else:
38+
# right sorted portion
39+
right = mid - 1
40+
return minVal
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def findPeakElement(self, nums: List[int]) -> int:
8+
"""
9+
A peak element is an element that is strictly greater than its neighbors.
10+
11+
Given a 0-indexed integer array nums, find a peak element, and return its index.
12+
If the array contains multiple peaks, return the index to any of the peaks.
13+
14+
You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is
15+
always considered to be strictly greater than a neighbor that is outside the
16+
array.
17+
18+
You must write an algorithm that runs in O(log n) time.
19+
"""
20+
left, right = 0, len(nums) - 1
21+
while left <= right:
22+
mid = (left + right) // 2
23+
midVal = nums[mid]
24+
leftVal = -float("inf") if mid == 0 else nums[mid - 1]
25+
rightVal = -float("inf") if mid == len(nums) - 1 else nums[mid + 1]
26+
27+
if leftVal < midVal and rightVal < midVal:
28+
return mid
29+
elif rightVal > midVal:
30+
left = mid + 1
31+
elif leftVal > midVal:
32+
right = mid - 1
33+
34+
return -1
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def search(self, nums: List[int], target: int) -> int:
8+
"""
9+
There is an integer array nums sorted in ascending order (with distinct values).
10+
11+
Prior to being passed to your function, nums is possibly rotated at an unknown
12+
pivot index k (1 <= k < nums.length) such that the resulting array is
13+
[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]
14+
(0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and
15+
become [4,5,6,7,0,1,2].
16+
17+
Given the array nums after the possible rotation and an integer target, return
18+
the index of target if it is in nums, or -1 if it is not in nums.
19+
20+
You must write an algorithm with O(log n) runtime complexity.
21+
"""
22+
left, right = 0, len(nums) - 1
23+
while left <= right:
24+
mid = (left + right) // 2
25+
26+
if target == nums[mid]:
27+
return mid
28+
29+
# left sorted portion
30+
if nums[left] <= nums[mid]:
31+
if target > nums[mid] or target < nums[left]:
32+
left = mid + 1
33+
else:
34+
right = mid - 1
35+
else:
36+
# right sorted portion
37+
if target < nums[mid] or target > nums[right]:
38+
right = mid - 1
39+
else:
40+
left = mid + 1
41+
return -1
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def searchRange(self, nums: List[int], target: int) -> List[int]:
8+
"""
9+
Given an array of integers nums sorted in non-decreasing order, find the
10+
starting and ending position of a given target value.
11+
12+
If target is not found in the array, return [-1, -1].
13+
14+
You must write an algorithm with O(log n) runtime complexity.
15+
"""
16+
# start position
17+
found = False
18+
left, right = 0, len(nums) - 1
19+
while left <= right:
20+
mid = (left + right) // 2
21+
if nums[mid] == target:
22+
found = True
23+
right = mid - 1
24+
elif nums[mid] > target:
25+
right = mid - 1
26+
else:
27+
left = mid + 1
28+
start = left
29+
30+
if not found:
31+
return [-1, -1]
32+
33+
# end position
34+
left, right = 0, len(nums) - 1
35+
while left <= right:
36+
mid = (left + right) // 2
37+
if nums[mid] <= target:
38+
left = mid + 1
39+
else:
40+
right = mid - 1
41+
end = right
42+
43+
return [start, end]
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
"""Base class for all LeetCode Problems."""
6+
7+
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
8+
"""
9+
Given two sorted arrays nums1 and nums2 of size m and n respectively, return
10+
the median of the two sorted arrays.
11+
12+
The overall run time complexity should be O(log (m+n)).
13+
"""
14+
total = len(nums1) + len(nums2)
15+
half = total // 2
16+
if len(nums2) < len(nums1):
17+
big, small = nums1, nums2
18+
else:
19+
big, small = nums2, nums1
20+
21+
left, right = 0, len(small) - 1
22+
while True:
23+
i = (left + right) // 2
24+
j = half - i - 2
25+
26+
leftSmall = small[i] if i >= 0 else -float("inf")
27+
rightSmall = small[i + 1] if (i + 1) < len(small) else float("inf")
28+
leftBig = big[j] if j >= 0 else -float("inf")
29+
rightBig = big[j + 1] if (j + 1) < len(big) else float("inf")
30+
31+
if leftSmall <= rightBig and leftBig <= rightSmall:
32+
if total % 2:
33+
return min(rightSmall, rightBig)
34+
else:
35+
return (max(leftSmall, leftBig) + min(rightSmall, rightBig)) / 2
36+
elif leftSmall > rightBig:
37+
right = i - 1
38+
else:
39+
left = i + 1
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._153_find_minimum_in_rotated_sorted_array import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "expected"],
10+
argvalues=[
11+
([3, 4, 5, 1, 2], 1),
12+
([4, 5, 6, 7, 0, 1, 2], 0),
13+
([11, 13, 15, 17], 11),
14+
([5, 1, 2, 3, 4], 1),
15+
],
16+
)
17+
def test_func(nums: List[int], expected: int):
18+
"""Tests the solution of a LeetCode problem."""
19+
min_val = Solution().findMin(nums)
20+
assert min_val == expected
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._162_find_peak_element import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "expected"],
10+
argvalues=[
11+
([1, 2, 3, 1], 2),
12+
([1, 2, 1, 3, 5, 6, 4], 5),
13+
],
14+
)
15+
def test_func(nums: List[int], expected: int):
16+
"""Tests the solution of a LeetCode problem."""
17+
peak_idx = Solution().findPeakElement(nums)
18+
assert peak_idx == expected
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from typing import List
2+
3+
import pytest
4+
5+
from awesome_python_leetcode._33_search_in_rotated_sorted_array import Solution
6+
7+
8+
@pytest.mark.parametrize(
9+
argnames=["nums", "target", "expected"],
10+
argvalues=[
11+
([4, 5, 6, 7, 0, 1, 2], 0, 4),
12+
([4, 5, 6, 7, 0, 1, 2], 3, -1),
13+
([1], 0, -1),
14+
],
15+
)
16+
def test_func(nums: List[int], target: int, expected: int):
17+
"""Tests the solution of a LeetCode problem."""
18+
idx = Solution().search(nums, target)
19+
assert idx == expected
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# flake8: noqa
2+
from typing import List
3+
4+
import pytest
5+
6+
from awesome_python_leetcode._34_find_first_and_last_position_of_element_in_sorted_array import (
7+
Solution,
8+
)
9+
10+
11+
@pytest.mark.parametrize(
12+
argnames=["nums", "target", "expected"],
13+
argvalues=[
14+
([5, 7, 7, 8, 8, 10], 8, [3, 4]),
15+
([5, 7, 7, 8, 8, 10], 6, [-1, -1]),
16+
([], 0, [-1, -1]),
17+
],
18+
)
19+
def test_func(nums: List[int], target: int, expected: List[int]):
20+
"""Tests the solution of a LeetCode problem."""
21+
ranges = Solution().searchRange(nums, target)
22+
assert ranges == expected

0 commit comments

Comments
 (0)