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.
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 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.
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 firstname.lastname@example.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.
- Distance between two closest minimum
- Find closest value for every element in array
- Find closest smaller value for every element in array
- Find closest greater value for every element in array
- Closest greater or same value on left side for every element in array
- Closest greater element for every array element from another array
- Maximum distance between two occurrences of same element in array
- Two elements whose sum is closest to zero
- Subarray whose sum is closest to K
- Find the Sub-array with sum closest to 0
- Subarray whose absolute sum is closest to K
- Find k closest elements to a given value
- Bitwise AND of sub-array closest to K
- Find closest number in array
- Closest product pair in an array