Created
April 25, 2021 09:55
-
-
Save KingAshiru/d1544a85acb9fc1bf938db5c29d14c73 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def findPosition(self, array, val): | |
position = [-1, -1] | |
if not array or not val: | |
return position | |
if type(val) is not int: | |
return position | |
if len(array) == 0: | |
return position | |
array.sort() | |
left = 0 | |
right = len(array) - 1 | |
i = 0 | |
#We iterate using a pointer from the left and another from the right, we break out of the loop immediately | |
#start and end positions are found to avoid doing unnecessary work. | |
while i < len(nums): | |
if position[0] != -1 and position[1] != -1: | |
break | |
if position[0] == -1: | |
if nums[left] == target: | |
position[0] = left | |
if position[1] == -1: | |
if nums[right] == target: | |
position[1] = right | |
left += 1 | |
right -= 1 | |
i += 1 | |
return position | |
#Time O(NlogN) | |
#Space O(logN) or O(N) depending on python sort function | |
#A binary search might have made sense if the array was pre-sorted, but since we had to sort ourself, | |
#we would always end up with O(NlogN) no matter how the search is implemented. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @KingAshiru, thank you for participating in Week 3 of #AlgorithmFridays.
Your solution looks clean, is robust and passes most of the test cases.
However, with regards to optimizing your solution, what effect do you think sorting the array (on line 11) has on your solution? Do you think you would have come up with a much better solution without sorting the array?
I have written a blog post here sharing my solution to this problem - a solution that avoids having to sort the array. Please read through and let me know what you think.
I hope this was a good learning experience for you. Thank you once again for participating once again and see you on Friday for Week 4 of #AlgorithmFridays.