Skip to content

Comments

Completed all 3 solution#2312

Open
avcode3 wants to merge 1 commit intosuper30admin:masterfrom
avcode3:master
Open

Completed all 3 solution#2312
avcode3 wants to merge 1 commit intosuper30admin:masterfrom
avcode3:master

Conversation

@avcode3
Copy link

@avcode3 avcode3 commented Feb 7, 2026

No description provided.

@super30admin
Copy link
Owner

Your solution for Problem 1 is correct and efficient. You have correctly implemented two binary search functions to find the first and last occurrences. The code is clean and readable. Well done!

One suggestion for improvement: you can optimize the search for the last occurrence by starting from the first occurrence found (if it exists) instead of starting from the beginning. For example, if you have found the first occurrence at index first, then you know the last occurrence must be at first or to the right. So you can call rightBinary with low = first instead of low = 0. This might reduce the number of comparisons in some cases.

Also, note that in the leftBinary function, the condition if mid == low or nums[mid-1] != nums[mid] is correct. However, using mid == 0 (as in the reference solution) is equally clear and might be slightly more straightforward. Similarly for rightBinary, you can use mid == len(nums)-1 but your condition mid == high is also correct because the high passed in is the last index of the current segment. Since the initial call passes the entire array, it is correct.

Overall, your solution is excellent.

@super30admin
Copy link
Owner

Your solution for Problem 1 is correct and efficient. Well done! Here are a few points to consider:

  • The code is clean and easy to understand. The use of helper functions for the left and right binary searches is a good approach.
  • One optimization you could make is to use the first occurrence index as the starting point for the right binary search. Currently, you are searching the entire array for the right boundary. Since the array is sorted, the last occurrence must be at or after the first occurrence. So, you can call self.rightBinary(nums, first, high, target) where first is the result from leftBinary. This might reduce the search range for the right binary search.
  • In the condition if mid == low or nums[mid-1] != nums[mid], it is correct, but note that if mid is 0, then mid-1 would be out of bounds. However, you have mid == low which in that case would be true (since low is 0), so it avoids the index error. This is safe. Similarly for the right binary search.
  • For consistency, you might consider using the same variable names as the reference solution (e.g., first and last) but this is minor.

Overall, your solution is excellent. Keep up the good work!

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.

2 participants