✅ Why is my code still wrong?
So I am resolving this LC puzzle https://leetcode.com/problems/binary-search/description/
I think my code is almost there, it still comes with a couple of failed test cases like this (see the attached screenshot).
Could anyone kindly point me in the right direction?
LeetCode
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
10 Replies
why are you using FindIndex when it asks for binary search
but to actually answer the question, the cause is the second if statement, the one inside the else block
@morry329
also why are u using FindIndex, that is O(n)
you can solve this exercise with 1 line
with Array.IndexOf
but it's still O(n)
the challenge is to make it better
1 line
a good way to approach this is to use the fact that the array is sorted to your advantage
so slice it
check that index vs the target and see where to go
left or right
sorry didn't see this lineWas this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.Ahhh thank you so much for your insights people! I am a stupid beginner one so I did not understand how FindIndex works. So this FindIndex was not necessary as the array has been already sorted for me, right?
that's not binary search what you did there
it's okay, what we meant is that using FindIndex or IndexOf is not a
proper
solution because they are O(n), and the task required O (log n).
since you are provided a sorted array you should take advantage of that
in this case, specifically with binary search
which only works on sorted arrays
and happens to be an algorithm at O (log are built in methods for binary search
you can check the Array class
but there is no fun in doing that, and it won't hold at an interview
you have 2 ways to handle this
1. you can check Array.BinarySearch method source code and try to understand it
or
2. check something like geekforgeeks
https://www.geeksforgeeks.org/binary-search/
https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Array.csWas this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.Thank you so much for the links -- one more question with regards to the time complexity. So the binary search on geeksforgeeks is at O (log n) as the algorithm divides the working area in half with each iteration (like the use of middle index)?
yes, you are taking chunks, taking advantage of the sorted array
you never traverse the array completely
so it's better than linear
Ahhh I got it 🙂 Thank you so much for explaining that to me