Distance of closest zero to every element

Given an array of n integers, for each element, print the distance to the closest zero. Array has a minimum of 1 zero in it.

Examples:

Input: 5 6 0 1 -2 3 4
Output: 2 1 0 1 2 3 4 
Explanation : The nearest 0(indexed 2) to 
5(indexed 0) is at a distance of 2, so we 
print 2. Same is done for the rest of elements.

Naive Approach: A naive approach is, for every element, slide towards left and find out the nearest 0 and again slide towards the right to find out the nearest zero if any, and print the minimum of both the distances. It will be space efficient but the time complexity will be high as we have to iterate for every element till we find the 0, and in worst case we may not find in one direction.
Time Complexity: O(n^2)
Auxiliary Space: O(1)

 

Efficient Approach: An efficient approach is to use sliding window technique two time. One is traversing from right to left and other from left right.
Initialize ans[0] with a max value. Iterate over array from left to right. If value in current position is 0, then set distance to 0, otherwise increase distance by 1. In each step, write value of distance to the answer array.
Do the same thing but going from right to left. This will find closest zero to the right. Now we should store the minimum of current value of distance and value that’s already in answer array.
Below is the implementation of the above approach.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find closest 0 for every element
#include <bits/stdc++.h>
using namespace std;
  
// Print the distance with zeroes of every element
void print_distance(int arr[], int n)
{
    // initializes an array of size n with 0
    int ans[n];
    memset(arr, 0, sizeof(arr));
  
    // if first element is 0 then the distance
    // will be 0
    if (arr[0] == 0)
        ans[0] = 0;
    else
        ans[0] = INT_MAX; // if not 0 then initialize 
                          // with a maximum value
  
    // traverse in loop from 1 to n and store 
    // the distance from left
    for (int i = 1; i < n; ++i) {
  
        // add 1 to the distance from previous one
        ans[i] = ans[i - 1] + 1;
  
        // if the present element is 0 then distance
        // will be 0
        if (arr[i] == 0) 
            ans[i] = 0;        
    }
  
    // if last element is zero then it will be 0 else 
    // let the answer be what was found when traveled
    // form left to right
    if (arr[n - 1] == 0)
        ans[n - 1] = 0;
  
    // traverse from right to left and store the minimum
    // of distance if found from right to left or left
    // to right
    for (int i = n - 2; i >= 0; --i) {
  
        // store the minimum of distance from left to
        // right or right to left
        ans[i] = min(ans[i], ans[i + 1] + 1);
  
        // if it is 0 then minimum will always be 0
        if (arr[i] == 0) 
            ans[i] = 0;
    }
  
    // print the answer array
    for (int i = 0; i < n; ++i) 
        cout << ans[i] << " ";    
}
  
// driver program to test the above function
int main()
{
    int a[] = { 2, 1, 0, 3, 0, 0, 3, 2, 4 };
    int n = sizeof(a) / sizeof(a[0]);
    printDistances(a, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find closest
// 0 for every element
import java.util.Arrays;
  
class GFG
{
    // Print the distance with zeroes of every element
    static void print_distance(int arr[], int n)
    {
        // initializes an array of size n with 0
        int ans[]=new int[n];
        Arrays.fill(ans,0);
      
        // if first element is 0 then the distance
        // will be 0
        if (arr[0] == 0)
            ans[0] = 0;
          
        // if not 0 then initialize 
        // with a maximum value    
        else
            ans[0] = +2147483647;
      
        // traverse in loop from 1 to n and store 
        // the distance from left
        for (int i = 1; i < n; ++i) 
        {
      
            // add 1 to the distance
            // from previous one
            ans[i] = ans[i - 1] + 1;
      
            // if the present element is 
            // 0 then distance will be 0
            if (arr[i] == 0
                ans[i] = 0;     
        }
      
        // if last element is zero 
        // then it will be 0 else 
        // let the answer be what was
        // found when traveled
        // form left to right
        if (arr[n - 1] == 0)
            ans[n - 1] = 0;
      
        // traverse from right to 
        // left and store the minimum
        // of distance if found from 
        // right to left or left
        // to right
        for (int i = n - 2; i >= 0; --i) 
        {
      
            // store the minimum of distance 
            // from left to right or right to left
            ans[i] = Math.min(ans[i], ans[i + 1] + 1);
      
            // if it is 0 then minimum 
            // will always be 0
            if (arr[i] == 0
                ans[i] = 0;
        }
      
        // print the answer array
        for (int i = 0; i < n; ++i) 
            System.out.print(ans[i] + " "); 
    }
      
    // Driver code 
    public static void main (String[] args)
    {
        int a[] = { 2, 1, 0, 3, 0, 0, 3, 2, 4 };
        int n = a.length;
        print_distance(a, n);
    }
}
  
// This code is contributed by Anant Agarwal.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find closest 0
# for every element
  
# Print the distance with zeroes of 
# every element
def print_distance(arr, n):
      
    # initializes an array of size n with 0
    ans = [0 for i in range(n)]
      
    # if first element is 0 then the 
    # distance will be 0
    if (arr[0] == 0):
        ans[0] = 0
    else:
        ans[0] = 10**9  # if not 0 then initialize 
                        # with a maximum value
  
    # traverse in loop from 1 to n and 
    # store the distance from left
    for i in range(1, n):
  
        # add 1 to the distance from 
        # previous one
        ans[i] = ans[i - 1] + 1
  
        # if the present element is 0 then 
        # distance will be 0
        if (arr[i] == 0):
            ans[i] = 0
  
    # if last element is zero then it will be 0 
    # else let the answer be what was found when 
    # traveled form left to right
    if (arr[n - 1] == 0):
        ans[n - 1] = 0
  
    # traverse from right to left and store 
    # the minimum of distance if found from 
    # right to left or left to right
    for i in range(n - 2, -1, -1):
  
        # store the minimum of distance from 
        # left to right or right to left
        ans[i] = min(ans[i], ans[i + 1] + 1)
  
        # if it is 0 then minimum will 
        # always be 0
        if (arr[i] == 0):
            ans[i] = 0
      
    # print the answer array
    for i in ans:
        print(i, end = " ")
  
# Driver Code
a = [2, 1, 0, 3, 0, 0, 3, 2, 4]
n = len(a)
print_distance(a, n)
  
# This code is contributed 
# by Mohit Kumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find closest
// 0 for every element
using System;
class GFG
{
    // Print the distance with zeroes of every element
    static void print_distance(int []arr, int n)
    {
        // initializes an array of size n with 0
        int []ans=new int[n];
        for(int i = 0; i < n; i++)
            ans[i] = 0;
  
        // if first element is 0 then the distance
        // will be 0
        if (arr[0] == 0)
            ans[0] = 0;
          
        // if not 0 then initialize 
        // with a maximum value 
        else
            ans[0] = +2147483646;
      
        // traverse in loop from 1 to n and store 
        // the distance from left
        for (int i = 1; i < n; ++i) 
        {
      
            // add 1 to the distance
            // from previous one
            ans[i] = ans[i - 1] + 1;
      
            // if the present element is 
            // 0 then distance will be 0
            if (arr[i] == 0) 
                ans[i] = 0;     
        }
      
        // if last element is zero 
        // then it will be 0 else 
        // let the answer be what was
        // found when traveled
        // form left to right
        if (arr[n - 1] == 0)
            ans[n - 1] = 0;
      
        // traverse from right to 
        // left and store the minimum
        // of distance if found from 
        // right to left or left
        // to right
        for (int i = n - 2; i >= 0; --i) 
        {
      
            // store the minimum of distance 
            // from left to right or right to left
            ans[i] = Math.Min(ans[i], ans[i + 1] + 1);
      
            // if it is 0 then minimum 
            // will always be 0
            if (arr[i] == 0) 
                ans[i] = 0;
        }
      
        // print the answer array
        for (int i = 0; i < n; ++i) 
            Console.Write(ans[i] + " "); 
    }
      
    // Driver code 
    public static void Main (String[] args)
    {
        int []a = { 2, 1, 0, 3, 0, 0, 3, 2, 4 };
        int n = a.Length;
        print_distance(a, n);
    }
}
  
// This code is contributed by PrinciRaj1992

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find closest 0 
// for every element 
  
// Print the distance with zeroes
// of every element 
function print_distance($arr, $n
    // initializes an array of size n with 0 
    $ans[$n] = array(); 
  
    $ans = array_fill(0, $n, true);
  
    // if first element is 0 then the 
    // distance will be 0 
    if ($arr[0] == 0) 
        $ans[0] = 0; 
    else
        $ans[0] = PHP_INT_MAX; // if not 0 then initialize 
                               // with a maximum value 
  
    // traverse in loop from 1 to n and 
    // store the distance from left 
    for ( $i = 1; $i < $n; ++$i
    
  
        // add 1 to the distance from 
        // previous one 
        $ans[$i] = $ans[$i - 1] + 1; 
  
        // if the present element is 0 
        // then distance will be 0 
        if ($arr[$i] == 0) 
            $ans[$i] = 0;     
    
  
    // if last element is zero then it will 
    // be 0 else let the answer be what was 
    // found when traveled form left to right 
    if ($arr[$n - 1] == 0) 
        $ans[$n - 1] = 0; 
  
    // traverse from right to left and store 
    // the minimum of distance if found from 
    // right to left or left to right 
    for ($i = $n - 2; $i >= 0; --$i)
    
  
        // store the minimum of distance from 
        // left to right or right to left 
        $ans[$i] = min($ans[$i], $ans[$i + 1] + 1); 
  
        // if it is 0 then minimum will 
        // always be 0 
        if ($arr[$i] == 0) 
            $ans[$i] = 0; 
    
  
    // print the answer array 
    for ($i = 0; $i < $n; ++$i
        echo $ans[$i] , " "
  
// Driver Code
$a = array( 2, 1, 0, 3, 0, 0, 3, 2, 4 ); 
$n = sizeof($a); 
print_distance($a, $n); 
  
// This code is contributed by Sachin
?>

chevron_right



Output:

2 1 0 1 0 0 1 2 3 

Time complexity: O(n)
Auxiliary Space: O(n)

This article is contributed by Raja Vikramaditya. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.