Maximum distance between adjacent 1s in given Binary String
Last Updated :
07 Nov, 2023
Given a binary string S containing N characters, the task is to find the maximum distance between two adjacent 1’s.
Examples:
Input: S = “1010010”
Output: 3
Explanation: There are 2 sets of adjacent 1’s in the given index on the indices {0, 2} and {2, 5}.
The one with the maximum distance among them is {2, 5} with a distance of 3 units.
Input: S = “100000”
Output: -1
Explanation: No set of adjacent 1’s exist in the given string.
Naive Approach:
The naive approach is to use two nested loops to find the distance between each adjacent 1’s. On getting the adjacent ones, update the maximum distance with the max of the previous maximum and current distance between the ones.
Algorithm:
1. Create a function to find the maximum distance between two adjacent 1’s, that takes a binary string S as input.
2. Initialize variables maxDist to -1.
3. Traverse the string S:
a. If the current character is 1:
Traverse the string S from the current index to the end:
If the next character is 1:
i. Calculate the distance between the current and next 1.
ii. Update the maximum distance if the current distance is greater than the previous maximum.
iii. Break out of the inner loop as we have found the next 1.
4. Return the maximum distance.
Below is the implementation of the approach:
C++
#include<bits/stdc++.h>
using namespace std;
int maxDistance(string s) {
int n = s.length();
int maxDist = -1;
for ( int i=0; i<n; i++) {
if (s[i] == '1' ) {
for ( int j=i+1; j<n; j++) {
if (s[j] == '1' ) {
int dist = j - i;
maxDist = max(maxDist, dist);
break ;
}
}
}
}
return maxDist;
}
int main() {
string S = "1010010" ;
cout << maxDistance(S) << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
public static int maxDistance(String s) {
int n = s.length();
int maxDist = - 1 ;
for ( int i = 0 ; i < n; i++) {
if (s.charAt(i) == '1' ) {
for ( int j = i + 1 ; j < n; j++) {
if (s.charAt(j) == '1' ) {
int dist = j - i;
maxDist = Math.max(maxDist, dist);
break ;
}
}
}
}
return maxDist;
}
public static void main (String[] args) {
String S = "1010010" ;
System.out.println(maxDistance(S));
}
}
|
Python
def maxDistance(s):
n = len (s)
max_dist = - 1
i = 0
while i < n:
if s[i] = = '1' :
j = i + 1
while j < n:
if s[j] = = '1' :
dist = j - i
max_dist = max (max_dist, dist)
break
j + = 1
i = j
else :
i + = 1
return max_dist
if __name__ = = "__main__" :
S = "1010010"
print (maxDistance(S))
|
C#
using System;
class Program
{
static int MaxDistance( string s)
{
int n = s.Length;
int maxDist = -1;
for ( int i = 0; i < n; i++)
{
if (s[i] == '1' )
{
for ( int j = i + 1; j < n; j++)
{
if (s[j] == '1' )
{
int dist = j - i;
maxDist = Math.Max(maxDist, dist);
break ;
}
}
}
}
return maxDist;
}
static void Main( string [] args)
{
string S = "1010010" ;
Console.WriteLine(MaxDistance(S));
}
}
|
Javascript
function maxDistance(s) {
const n = s.length;
let maxDist = -1;
for (let i = 0; i < n; i++) {
if (s.charAt(i) === '1' ) {
for (let j = i + 1; j < n; j++) {
if (s.charAt(j) === '1' ) {
const dist = j - i;
maxDist = Math.max(maxDist, dist);
break ;
}
}
}
}
return maxDist;
}
const S = "1010010" ;
console.log(maxDistance(S));
|
Time Complexity: O(N*N) as two nested loops are executing. Here, N is size of input binary string.
Space Complexity: O(1) as no extra space has been used.
Approach: The given problem is an implementation-based problem. The idea is to store all the indices of 1’s in increasing order in a vector. Hence it can be observed that the required answer will be the maximum of the difference of consecutive integers in the index vector.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
int maxDist(string S)
{
int maxLen = INT_MIN;
vector< int > indices;
for ( int i = 0; i < S.length(); i++) {
if (S[i] == '1' )
indices.push_back(i);
}
for ( int i = 1; i < indices.size(); i++)
maxLen = max(maxLen, indices[i] -
indices[i - 1]);
return maxLen == INT_MIN ? -1 : maxLen;
}
int main()
{
string S = "1010010" ;
cout << maxDist(S);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
public static int maxDist(String S)
{
int maxLen = Integer.MIN_VALUE;
Vector<Integer> indices = new Vector<Integer>();
for ( int i = 0 ; i < S.length(); i++) {
if (S.charAt(i) == '1' )
indices.add(i);
}
for ( int i = 1 ; i < indices.size(); i++)
maxLen = Math.max(maxLen, indices.get(i) -
indices.get(i - 1 ));
return maxLen == Integer.MIN_VALUE ? - 1 : maxLen;
}
public static void main (String[] args)
{
String S = "1010010" ;
System.out.println(maxDist(S));
}
}
|
Python3
def maxDist(S):
maxLen = 10 * * - 9
indices = []
for i in range ( len (S)):
if S[i] = = "1" :
indices.append(i)
for i in range ( 1 , len (indices)):
maxLen = max (maxLen, indices[i] - indices[i - 1 ])
return - 1 if (maxLen = = 10 * * - 9 ) else maxLen
S = "1010010"
print (maxDist(S))
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static int maxDist( string S)
{
int maxLen = Int32.MinValue;
List< int > indices = new List< int >();
for ( int i = 0; i < S.Length; i++) {
if (S[i] == '1' )
indices.Add(i);
}
for ( int i = 1; i < indices.Count; i++)
maxLen = Math.Max(maxLen, indices[i] -
indices[i - 1]);
if (maxLen == Int32.MinValue)
return -1;
else
return maxLen;
}
static public void Main ()
{
string S = "1010010" ;
Console.WriteLine(maxDist(S));
}
}
|
Javascript
<script>
function maxDist(S)
{
let maxLen = Number.MIN_VALUE;
let indices = [];
for (let i = 0; i < S.length; i++) {
if (S[i] == '1')
indices.push(i);
}
for (let i = 1; i < indices.length; i++)
maxLen = Math.max(maxLen, indices[i] -
indices[i - 1]);
return maxLen == Number.MIN_VALUE ? -1 : maxLen;
}
let S = "1010010" ;
document.write(maxDist(S));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N) where N is the length of the Binary String.
Space-Efficient Approach: The above approach can also be implemented without using any extra space (vector). The only change is to achieve maximum distance by rigorous difference storing and updation every time we found 1 in the binary string.
C++14
#include <bits/stdc++.h>
using namespace std;
int maxDist(string S)
{
int maxLen=0,i,start=0;
for ( i = 0; i < S.length(); i++) {
if (S[i] == '1' )
{
start=i;
break ;
}
}
for (; i < S.length(); i++){
if (S[i] == '1' )
{
maxLen=max(maxLen,i-start);
start=i;
}
}
return maxLen == 0 ? -1 : maxLen;
}
int main()
{
string S = "100000" ;
cout << maxDist(S);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int maxDist(String S)
{
int maxLen= 0 ,i,start= 0 ;
for ( i = 0 ; i < S.length(); i++) {
if (S.charAt(i) == '1' )
{
start=i;
break ;
}
}
for (; i < S.length(); i++){
if (S.charAt(i) == '1' )
{
maxLen=Math.max(maxLen,i-start);
start=i;
}
}
return maxLen == 0 ? - 1 : maxLen;
}
public static void main(String[] args)
{
String S = "100000" ;
System.out.print(maxDist(S));
}
}
|
Python3
def maxDist(S):
maxLen = 0 ;
start = 0 ;
for i in range ( len (S)):
if (S[i] = = '1' ):
start = i;
break ;
for i in range (start, len (S)):
if (S[i] = = '1' ):
maxLen = max (maxLen, i - start);
start = i;
if (maxLen = = 0 ):
return - 1 ;
else :
return maxLen;
if __name__ = = '__main__' :
S = "100000" ;
print (maxDist(S));
|
C#
using System;
public class GFG {
static public int maxDist(String S)
{
int maxLen = 0, i, start = 0;
for (i = 0; i < S.Length; i++) {
if (S[i] == '1' ) {
start = i;
break ;
}
}
for (; i < S.Length; i++) {
if (S[i] == '1' ) {
maxLen = Math.Max(maxLen, i - start);
start = i;
}
}
return maxLen == 0 ? -1 : maxLen;
}
public static void Main(String[] args) {
String S = "100000" ;
Console.Write(maxDist(S));
}
}
|
Javascript
<script>
function maxDist( S)
{
var maxLen = 0, i, start = 0;
for (i = 0; i < S.length; i++) {
if (S.charAt(i) == '1 ') {
start = i;
break;
}
}
// Loop to traverse remaining
// indices of character ' 1 '
for (; i < S.length; i++) {
// Update maximum distance
if (S.charAt(i) == ' 1') {
maxLen = Math.max(maxLen, i - start);
start = i;
}
}
return maxLen == 0 ? -1 : maxLen;
}
var S = "100000" ;
document.write(maxDist(S));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1), where N is the length of the Binary String.
Share your thoughts in the comments
Please Login to comment...