Distance of closest zero to every element - GeeksforGeeks

22 Feb, 2022
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++
Java
Python3
C#
PHP
Javascript
// CPP program to find closest 0 for every element#include <bits/stdc++.h>using namespace std; // Print the distance with zeroes of every elementvoid 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    // from 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 functionint main(){    int a[] = { 2, 1, 0, 3, 0, 0, 3, 2, 4 };    int n = sizeof(a) / sizeof(a[0]);    printDistances(a, n);    return 0;}
// Java program to find closest// 0 for every elementimport 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        // from 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.
# Python3 program to find closest 0# for every element # Print the distance with zeroes of# every elementdef 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 from 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 Codea = [2, 1, 0, 3, 0, 0, 3, 2, 4]n = len(a)print_distance(a, n) # This code is contributed# by Mohit Kumar
// C# program to find closest// 0 for every elementusing 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        // from 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
<?php// PHP program to find closest 0// for every element // Print the distance with zeroes// of every elementfunction 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 from 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?>
<script>// javascript 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        var ans = Array(n).fill(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 (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        // from 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] = 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 (i = 0; i < n; ++i)            document.write(ans[i] + " ");    }     // Driver code        var a = [ 2, 1, 0, 3, 0, 0, 3, 2, 4 ];        var n = a.length;        print_distance(a, n); // This code is contributed by Rajput-Ji</script>
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 write.geeksforgeeks.org or mail your article to review-team@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. 
Sach_Code
princiraj1992
mohit kumar 29
Rajput-Ji
arorakashish0911
simmytarika5
sliding-window
Arrays
sliding-window
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Move all negative numbers to beginning and positive to end with constant extra space
Program to find sum of elements in a given array
Building Heap from Array
Find duplicates in O(n) time and O(1) extra space | Set 1
Next Greater Element
Count pairs with given sum
Remove duplicates from sorted array