Binary Search (Leetcode 704):
To solve the binary search problem, we cut a sorted array into halves recursively thus achevie a time complexity of N(nlog(n)).
left closed right closed
class Solution:
def search(self, nums: List[int], target: int) -> int:
start = 0
end = len(nums) - 1
while(start<=end):
mid = (start + end )//2
if nums[mid] == target:
return mid
if nums[mid] < target:
start = mid +1
if nums[mid] > target:
end = mid - 1
return -1
left closed right open
in this case, the last index is a phamton, when update end point, use mid instead of mid -1, because the value is at end -1.
class Solution:
def search(self, nums: List[int], target: int) -> int:
start, end = 0, len(nums)
while(start < end):
mid = start + (end - start)//2
if nums[mid] == target:
return mid
if nums[mid] < target:
start = mid + 1
if nums[mid] > target:
end = mid
return -1
Remove Element (LeetCode 27)
The brutal way to solve the problem will be implementing two iterations. The first one find the target value, and the second iteration move all of the rest elements forward by one. This will give a time complexity of N(n^2)
to implement a sliding window, we need to have two pointers. The fast pointer iterate trough the the array, the slow pointer is updated only when the fast pointer is not at the target value. in such a case the slow pointer will be assigned a value from the fatser pointer. if the fast pointer is at the target value. then the slow pointer doesn't update. This will give a time complexity of N(n)
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
fast = 0
slow = 0
length = len(nums)
while fast<length:
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
Another way to solve this problem is iterate through the list. if find val, replace the last element with val and shrink the valid array size by one. (mark off the last elements so no repeat). We can solve the problem this way only because the problem definition only asking for the length of the the valid array and assume that we can swap the elements orders.
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
size = len(nums)
i = 0
while(i < size):
if nums[i] == val:
nums[i] = nums[size-1]
size = size -1
else:
i = i + 1
return size