binary search 1#2486
Conversation
Search inside a Rotated Sorted Array (rotated-sorted-array.py)Your solution is well-structured and efficient. It correctly implements the binary search algorithm for a rotated sorted array. The time and space complexity are optimal. However, the comments in your code are a bit unclear and could be improved. For example, the comment VERDICT: PASS Search Inside a Sorted Array whose Length is unknown (sorted-array-unknown-size.py)Strengths:
Areas for improvement:
Corrected code should look like: class Solution:
def search(self, reader: 'ArrayReader', target: int) -> int:
left = 0
right = 1
# Expand the right bound until we are beyond the target or out of bounds
while reader.get(right) < target:
left = right
right *= 2
# Now perform binary search between left and right
while left <= right:
mid = left + (right - left) // 2
mid_val = reader.get(mid)
if mid_val == target:
return mid
elif mid_val < target:
left = mid + 1
else:
right = mid - 1
return -1VERDICT: NEEDS_IMPROVEMENT Search a 2D Matrix (search-2d-matrix.py)Your solution is well-structured and correctly implements the two-step binary search approach. Here are some points to consider for improvement:
Suggested improvements:
Here is a slightly refined version of your code for clarity: class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
cols = len(matrix[0])
rows = len(matrix)
top, bot = 0, rows - 1
row = -1
while top <= bot:
mid_row = top + (bot - top) // 2
if matrix[mid_row][0] > target:
bot = mid_row - 1
elif matrix[mid_row][-1] < target:
top = mid_row + 1
else:
row = mid_row
break
if row == -1:
return False
left, right = 0, cols - 1
while left <= right:
mid_col = left + (right - left) // 2
if matrix[row][mid_col] == target:
return True
if matrix[row][mid_col] < target:
left = mid_col + 1
else:
right = mid_col - 1
return FalseThis version uses VERDICT: PASS |
No description provided.