In Python interviews, understanding common algorithms like binary search is crucial for demonstrating problem-solving efficiency—often asked to optimize time complexity from O(n) to O(log n) for sorted data, showing your grasp of divide-and-conquer strategies.
#python #algorithms #binarysearch #interviews #timescomplexity #problemsolving
👉 @DataScience4
# Basic linear search (O(n) - naive approach)
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
nums = [1, 3, 5, 7, 9]
print(linear_search(nums, 5)) # Output: 2
# Binary search (O(log n) - efficient for sorted arrays)
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right: # Divide range until found or empty
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1 # Search right half
else:
right = mid - 1 # Search left half
return -1
sorted_nums = [1, 3, 5, 7, 9]
print(binary_search(sorted_nums, 5)) # Output: 2
print(binary_search(sorted_nums, 6)) # Output: -1 (not found)
# Edge cases
print(binary_search([], 1)) # Output: -1 (empty list)
print(binary_search(, 1)) # Output: 0 (single element)
#python #algorithms #binarysearch #interviews #timescomplexity #problemsolving
👉 @DataScience4
❤4