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.
Similar Reads
Maximum distance between two 1s in a Binary Array in a given range
Given a binary array of size N and a range in [l, r], the task is to find the maximum distance between two 1s in this given range.Examples: Input: arr = {1, 0, 0, 1}, l = 0, r = 3 Output: 3 In the given range from 0 to 3, first 1 lies at index 0 and last at index 3. Hence, maximum distance = 3 - 0 =
14 min read
Maximum distance between two 1's in Binary representation of N
Given a number N, the task is to find the maximum distance between two 1's in the binary representation of given N. Print -1 if binary representation contains less than two 1's.Examples: Input: N = 131 Output: 7 131 in binary = 10000011. The maximum distance between two 1's = 7. Input: N = 8 Output:
5 min read
Max distance between first and last indexed element in Binary String
Given a binary string S of length N along with Y[] of size K. Then you have to perform K number of queries for each i (1 <= i <= K) where you have to output the maximum distance between the first and last indexed character of S among all the queries, by doing the following operation for each q
9 min read
Sum of the shortest distance between all 0s to 1 in given binary string
Given a binary string S, the task is to find the sum of the shortest distance between all 0s to 1 in the given string S. Examples: Input: S = "100100" Output: 5Explanation: For the '0' at index 1 the nearest '1' is at index 0 at a distance 1.For the '0' at index 2 the nearest '1' is at index 3 at a
11 min read
Maximizing Distance in Binary Strings
Given an array of binary strings arr[] of size N (1 <= N <= 103). The task is to find the maximum distance between any pair of these binary strings. The distance between two binary strings is calculated as the sum of their lengths after excluding the common prefix. Examples: Input: arr[] = { â
10 min read
Maximum 0's between two immediate 1's in binary representation
Given a number n, the task is to find the maximum 0's between two immediate 1's in binary representation of given n. Return -1 if binary representation contains less than two 1's. Examples : Input : n = 47 Output: 1 // binary of n = 47 is 101111 Input : n = 549 Output: 3 // binary of n = 549 is 1000
9 min read
Maximum difference of zeros and ones in binary string
Given a binary string of 0s and 1s. The task is to find the length of the substring which is having a maximum difference between the number of 0s and the number of 1s (number of 0s - number of 1s). In case of all 1s print -1. Examples: Input : S = "11000010001"Output : 6From index 2 to index 9, ther
15 min read
Minimum adjacent swaps required to make a binary string alternating
Given a binary string S of size N, the task is to find the number of minimum adjacent swaps required to make the string alternate. If it is not possible to do so, then print -1. Examples: Input: S = "10011"Output: 1Explanation:Swap index 2 and index 3 and the string becomes 10101 . Input: S = "11010
11 min read
Check if a binary string has a 0 between 1s or not | Set 1 (General approach)
Given a string of 0 and 1, we need to check that the given string is valid or not. The given string is valid when there is no zero present in between 1's. For example, 1111, 0000111110, 1111000 are valid strings but 01010011, 01010, 101 are not. One approach to solving the problem is discussed here,
11 min read
Maximize sum by multiplying adjacent difference of Binary String with any digit
Given a binary string S and a string of non-zero digits P of length N, the task is to maximize the sum using the given operations, which can be used as my times you can: You can choose a substring of length 2 or 3.Delete that substring after calculating the absolute difference of adjacent elements f
12 min read