Skip to content

binary search 1#2486

Open
spencerkrebs wants to merge 1 commit into
super30admin:masterfrom
spencerkrebs:master
Open

binary search 1#2486
spencerkrebs wants to merge 1 commit into
super30admin:masterfrom
spencerkrebs:master

Conversation

@spencerkrebs
Copy link
Copy Markdown

No description provided.

@super30admin
Copy link
Copy Markdown
Owner

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 # [6,0,1,2,3] and # [4,5,6,7,0,1,2] 6 do not provide much value and might be confusing. Consider adding comments that explain the logic rather than examples without context. Alternatively, you can remove them if they are just notes for yourself. Also, ensure that your variable names are consistent and clear. Overall, good job!

VERDICT: PASS


Search Inside a Sorted Array whose Length is unknown (sorted-array-unknown-size.py)

Strengths:

  • You have correctly identified the two-step approach: first find the bounds, then perform binary search.
  • You used appropriate variable names and maintained good code structure.

Areas for improvement:

  • There is a critical error in the first while loop: you used i which is not defined. You should use right instead. The condition should be while reader.get(right) < target to check if the current right bound is less than the target, indicating that we need to expand further.
  • Also, consider that the ArrayReader might return 2^31 - 1 for out-of-bound indices. Your loop condition should account for that to avoid infinite loops. However, in this case, since the array elements are unique and sorted, and the target is within [-10^4, 10^4], and 2^31 - 1 is a large number (2147483647), it is safe to compare directly. But note that if reader.get(right) returns 2^31 - 1, it means we are out of bounds, and we should stop expanding. However, in your condition, you are comparing with target, which is at most 10000, so reader.get(right) (which is 2147483647) will be greater than target, so the loop will stop. So it's acceptable.
  • Another point: when you set left = right and then right = right * 2, you are effectively doubling the search range. This is correct. But ensure that after finding the bounds, the binary search is performed correctly.

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 -1

VERDICT: 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:

  1. Unused Variable: You declared cols = len(matrix[0]) but did not use it. Instead, you used len(matrix[0]) again later. It's better to use the variable you defined to avoid redundant calculations and improve readability.

  2. Consistency: You defined rows = len(matrix) but then used rows - 1 for bot. However, when setting right in the second binary search, you used len(matrix[0])-1. It would be more consistent to use cols - 1 since you already defined cols.

  3. Clarity: The variable names top, bot, left, right are clear and descriptive. However, consider using low and high consistently for binary search variables to match common conventions.

  4. Efficiency: Your solution is efficient with O(log m + log n) time complexity, which is equivalent to O(log(m*n)) as required. The space complexity is O(1), which is optimal.

  5. Edge Cases: Your solution handles edge cases correctly, such as when the target is not found in any row (returning false) and when the target is found in the row.

Suggested improvements:

  • Use the defined cols variable in the second binary search: right = cols - 1.
  • Consider removing the rows variable if you are not using it consistently, but in this case, you did use it for bot, so it's fine.

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 False

This version uses mid_row and mid_col to make it clearer which index is being computed, and it stores the found row index in row instead of using a flag found. This reduces one variable and might be slightly more straightforward.

VERDICT: PASS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants