hey #viewers
Today marks my day 73, of solving a hard question everyday, for the next 75 days 🚀
Today, I solved a question named as Patching Array 😄
Leetcode : https://lnkd.in/g_gEEbNZ
This question was previously asked in many of the MNCs like Amazon 🏢
Approach :
• Basically, we have an array given, and a value as we need to find the elements, we need to add / patch, so that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.
• So, we can simply search, using a greedy approach, and try to make minimum patches, in the array.
· To do so, sabse pehle, assign the sum, as 1, because we need to add at least 1, as sum.
· Then, assign no of patches as 0 initially, and starting index, i as 0.
· Then, Iterate in a while loop, until sum is lesser than or equal to n, and check if the current element in nums, is less than or equal to sum, as it means we can use this element to extend the range we can cover. We add nums[i] to sum and move to the next element.
· Else, If nums[i] is greater than sum, it means we need to add a patch. The best patch to add in this situation is sum itself because it will maximize the extension of the range.
• So, just increment the number of patches by 1.
• Finally, return the number of patches.
Time complexity : O (n + log m)
Space complexity: O (1)
For further assistance, please find the code attached below ⬇️
In case of any queries, feel free to ask in the comments 🙂
We are just two more days ahead, of completing this challenge 🥳, let's see if we keep our pace right.
#ab #mai #hashTag #use #karunga #for #good #reach #and #thats #it #75hardchallenge #connections #codechallenge
Senior Manager - HR at Universal Technological Solutions Pvt. Ltd.
6moHappy Work Anniversary Akshada.