Minimum distance between two 1s in a range using a segment tree

Updated

Given a binary array consisting of only 0s and 1s, find the minimum distance between two elements with value 1 in a subarray {l,r}.

Examples :

Input : arr = {1,0,0,1}, l=0, r=3
Output : 3
Clearly, in the range from 0 to 3, first 1 lies at index 0 and last at
index 3.
Hence, the distance 3-0 =3.

Input : arr = {1,1,0,1,0,1,0,1,0,1,0,1,1,0}, l=3, r=9
Output : 2

Pre-requisite: Segment Trees

Approach :

  1. We will create a segment tree to solve this. Each node in the segment tree will have the index of leftmost 1 as well as rightmost 1 and an integer containing the minimum distance between any elements with value 1 in a subarray {l,r}.
  2. Now, in this segment tree we can merge left and right nodes as below:
    • If left node is not valid, return right node.
    • If right node is not valid, return left node.
    • A node is valid iff it contains at least one 1.
    • If both left and right nodes are valid then:
      Let,

      • l1 = leftmost index of 1 (-1 if 1 doesn’t exist in that interval)
      • r1 = rightmost index of 1 (-1 if 1 doesn’t exist in that interval)
      • min1 = minimum distance between two 1’s
      • Value of min1 in merged node will be minimum of minimum of value of min1 in left and right node, and difference between leftmost index of 1 in right node and rightmost index of 1 in left node.
      • Value of l1 in merged node will be l1 of left node if it is not -1, else l1 of right node.
      • Value of r1 in merged node will be r1 of right node if it is not -1, else r1 of left node.
  3. Then, finally to find the answer we just need to call query function for the given range {l,r}.
Segment tree for 1, 0, 0, 1 with l1, r1 and min1 in each node and the merge of two child nodes into the root where min1 becomes 3.

Implementation :

// C++ program to find the minimum 
// distance between two elements 
// with value 1 within a subarray (l,r)  
#include <bits/stdc++.h>
using namespace std;

// Structure for each node 
// in the segment tree
struct node{
    int l1, r1;
    int min1;
} seg[100001];


// A utility function for  
// merging two nodes
node task(node l, node r)
{
    node x;
    
    x.l1 = (l.l1!=-1)?l.l1:r.l1;
    
    x.r1 = (r.r1!=-1)?r.r1:l.r1;
    
    x.min1 = min(l.min1, r.min1);
    if(l.r1!=-1 && r.l1!=-1)
        x.min1=min(x.min1, r.l1-l.r1);
        
    return x;
}

// A recursive function that constructs  
// Segment Tree for given string 
void build(int qs , int qe , int ind, int arr[])
{
	// If start is equal to end then 
    // insert the array element 
    if(qs == qe)
    {
    	if(arr[qs]==1){
    		seg[ind].l1 = seg[ind].r1 =qs;
    		seg[ind].min1=INT_MAX;
		}
		else{
			seg[ind].l1 = seg[ind].r1 =-1;
    		seg[ind].min1=INT_MAX;
		}
    
        return;
    }
    int mid=(qs+qe)>>1;
    
    // Build the segment tree 
	//for range qs to mid 
    build(qs,mid,ind<<1,arr);
    
    // Build the segment tree 
	//for range mid+1 to qe
    build(mid+1,qe,ind<<1|1,arr);
    
    // merge the two child nodes 
       //to obtain the parent node
    seg[ind]=task(seg[ind<<1],seg[ind<<1|1]);
}

// Query in an range qs to qe 
node query( int qs , int qe , int ns , int ne , int ind )
{
    node x;
    x.l1=x.r1=-1;
    x.min1=INT_MAX;
    
    // If the range lies in this segment 
    if(qs<=ns && qe>=ne)
        return seg[ind];
	
	// If the range is out of the bounds 
    // of this segment 
    if(ne<qs || ns>qe || ns>ne )
        return x ;
	
	// Else query for the right and left 
    // child node of this subtree 
    // and merge them  
    int mid=(ns+ne)>>1;

    node l=query(qs,qe,ns,mid,ind<<1);
    node r=query(qs,qe,mid+1,ne,ind<<1|1);

    x=task(l,r);
    return x;
}

// Driver code 
int main() 
{ 
  
    int arr[] = {1,1,0,1,0,1,0,1,0,1,0,1,1,0}; 
    int n = sizeof(arr) / sizeof(arr[0]);  
  
    // Build the segment tree 
    build(0, n - 1, 1, arr); 
  
    // Query in range 3 to 9 
    node ans = query(3, 9, 0, n-1, 1); 
    
    cout<<ans.min1<<"\n";
  
    return 0; 
} 

Output :

2
Comment
Mithlesh Upadhyay Published 6 Dec 2026 · 4 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials