If the repeating sum is found, it means that there is a subarray between those two sums with a sum of 0. The hash_map helps to keep track of the cumulative sum and determine if there is any repeating sum. If loop completes, return false as there is no subarray with 0 sum. If the current sum is 0 or it is already present in the hash_map, return true as there is a subarray with 0 sum.Įlse, insert the sum value and its index to the hash_map. Loop through the given array, for each element − Initialize variables "sum" to 0 and "hash_map" object to store the sum values as keys and their indices as values. This way, we can determine if there is a subarray with 0 sum in an array. We will be continuously updating the hash map with the sum of elements seen so far. If the sum is seen before, it means that the subarray with this sum exists and has 0 sum. We will keep track of the sum of elements of the subarray seen so far and store it in a hash map. This can be done by using the concept of prefix sum. We, as developers, are often asked to find if there is a subarray with 0 sum in an array.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |