Skip to content
Advertisement

First occurrence of 1 in unsorted binary array

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.

JavaScript

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.

Advertisement

Answer

The problem you have is you don’t remember start of the array in subsequent call. To mitigate this issue you have to keep information about current position in original array. I would either add start index of array to the call result or just pass “position” of subarray with every call.

The base case you proposed at the end of the question should be fine ;) Nest time please say explicitly you want ‘divide and conquer’ solution, because of parallel processing. It would prevent proposals of simpler sequential solutions.

Example solution using divide and conquer:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement