Today I solved two problems:
1. Find Minimum in Rotated Sorted Array (LeetCode #153)
Python Solution:
class Solution:
def findMin(self, nums):
l, r = 0, len(nums) - 1
while l < r:
if nums[l] < nums[r]:
return nums[l]
mid = l + (r - l) // 2
if nums[mid] < nums[l]:
r = mid
else:
l = mid + 1
return nums[l]
Approach:
- Use binary search to locate the smallest element in the rotated sorted array.
- Compare
nums[l]
andnums[r]
to determine if the current range is sorted. - Adjust the search range based on comparisons with the mid element.
Learnings:
- Binary search is a powerful tool for logarithmic time complexity.
- Handling edge cases like no rotation or single-element arrays is crucial.
Other Approaches:
- A simple linear scan to find the minimum value, but it takes O(n)O(n) time.
2. Container with Most Water (LeetCode #11)
Python Solution:
class Solution:
def maxArea(self, height):
l, r = 0, len(height) - 1
maxWater = 0
while l < r:
maxWater = max(maxWater, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return maxWater
Approach:
- Use two pointers to maximize the area between the container walls.
- Calculate the area using the shorter wall height and width
(r - l)
. - Move the pointer pointing to the shorter wall inward to potentially increase the area.
Learnings:
- Two-pointer techniques effectively solve problems involving pairs of elements.
- Always consider edge cases, such as arrays with minimal size.
Other Approaches:
- A brute-force approach checking all possible pairs, which takes O(n2)O(n²) time.
Thanks to iCodeGuru for their help and support in my coding journey. Their guidance motivates me to keep learning and solving problems. Let’s grow together!