CONCEPTS USED:
Binary Search
DIFFICULTY LEVEL:
Easy
PROBLEM STATEMENT(SIMPLIFIED):
Given a sorted array of
0'sand1'sof sizeN, find the first occurrence of1if present else return-1.
For Example:
Input : arr = [0, 0, 0, 1, 1]
Output : 3
Explanation : First occurrence of 1 is present at 3rd index.
Can we use Binary Search here ?
Given that the array is sorted,
Binary Searchwould be an efficient alternative to quickly search for the first occurrence of1inLogarithmic Time Complexity.
SOLVING APPROACH:
The idea is to use
Binary Search.Initialize
mid = start + (end - start) / 2andflag =-1, wherestartis the starting index of the array andendis the last index.Check if
1is present atmidindex, if Yes save this index inflagand search for a smaller index by searching in the left sub array by marking,end = mid -1.Else keep on searching in the right half by marking
start=mid + 1.Keep doing it till
startbecomes less than equal toend, finally returnflag.
ALGORITHM:
flag = -1
while (start <= end)
mid = start + (end - start) / 2
if (element at mid index = 1)
flag = mid
end = mid - 1
else
start = mid + 1
return flag
SOLUTIONS:
#include <stdio.h>
int firstOccurence(int *arr, int start, int end, int flag){
while(start <= end){
int mid = start + (end - start) / 2;
if(arr[mid] == 1){
flag = mid;
end = mid - 1;
}
else{
start = mid + 1;
}
}
return flag;
}
int main()
{
int t; scanf("%d", &t);
while(t--){
int n; scanf("%d", &n);
int arr[n];
for(int i = 0; i<n; i++)
scanf("%d", &arr[i]);
printf("%d\n", firstOccurence(arr, 0, n-1,-1));
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int firstOccurence(int *arr, int start, int end, int flag = -1){
while(start <= end){
int mid = start + (end - start) / 2;
if(arr[mid] == 1){
flag = mid;
end = mid - 1;
}
else{
start = mid + 1;
}
}
return flag;
}
int main()
{
int t; cin>>t;
while(t--){
int n; cin>>n;
int arr[n];
for(int i = 0; i<n; i++)
cin>>arr[i];
cout<<firstOccurence(arr, 0, n-1)<<"\n";
}
return 0;
}
import java.util.*;
import java.io.*;
public class Main {
static int firstOccurence(int[] arr, int start, int end, int flag){
while(start <= end){
int mid = start + (end - start) / 2;
if(arr[mid] == 1){
flag = mid;
end = mid - 1;
}
else{
start = mid + 1;
}
}
return flag;
}
public static void main(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t != 0){
int n = sc.nextInt();
int arr[] = new int[n];
for(int i = 0; i<n; i++)
arr[i] = sc.nextInt();
System.out.println(firstOccurence(arr, 0, n-1, -1));
t--;
}
}
}
Space Complexity: O(1)
[forminator_quiz id="1651"]
This article tried to discuss Binary Search. Hope this blog helps you understand the concept. To practice more problems you can check out .
