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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Subarray whose absolute sum is closest to K
- Maximum Unique Element in every subarray of size K
- Count distinct elements in every window of size k
- Find maximum of minimum for every window size in a given array
- First negative integer in every window of size k
- Minimum bit flips such that every K consecutive bits contain at least one set bit
- Count of N digit Numbers whose sum of every K consecutive digits is equal
- Min difference between maximum and minimum element in all Y size subarrays
- Majority element in a circular array of 0's and 1's
- Longest subarray in which absolute difference between any two element is not greater than X
- Minimum cost required to convert all Subarrays of size K to a single element
- Substring of length K having maximum frequency in the given string
- Check if a subarray of size K exists whose elements form a number divisible by 3
- Queries to find maximum sum contiguous subarrays of given length in a rotating array