I am solving a problem to find the first 1 in an unsorted array of 1s and 0s. If any 1 is found program should return the index otherwise return -1. I would like to have divide and conquer solution for this problem, but I am struggling with the base case.
def first_one(A):
n = len(A)
leftmost = 0
if n <= 1:
# probably would be when n <=1 ? I was returning 0 if A[0] == 1 or n otherwise
# but this lead to the final result always being determined by the first index.
idx_left = first_one(A[:int(n/2)])
idx_right = first_one(A[int(n/2):])
result = min(idx_left, idx_right)
if result == n:
return -1
else:
return result
So what should my base case be - to retrieve the actual first index instead of 0 (or -1) all the time? I can't think of any other base case.