This is a companion discussion topic for the original entry at https://www.raywenderlich.com/11447782-kotlin-whiteboard/lessons/4
This is a companion discussion topic for the original entry at https://www.raywenderlich.com/11447782-kotlin-whiteboard/lessons/4
One quick correction on this solution: if the search value is not in the array, firstPosition
as written will not return null
but instead an actual value.
So consider the solution given as only working with the constraint that the value for which weβre searching for the range for is actually in the ArrayList
. If you encountered this question in an interview, that would be a good point to clarify with your interviewer: can you assume the target value given is in the list?
Hat tip to @gibels_and_bits for pointing out this issue!
in your example next element to the 3 was 4 so you tried to find the 4 get the range.last of 3 what if there is no 4 in the list, I mean we cannot assume next item to be searchItem+1
Hi @abhilash17, thanks for the question. The function firstPosition()
finds the first position in the array greater than or equal to a value. So 4 does not have to be in the array for it to work. We call it with 3 to find the first position of 3 in the array, and then with 4 to find the first position taken up by a value after 3.
@macsimus Thank you for sharing this - much appreciated!