Product of Array Except Self (LeetCode 238) | Full solution with visuals | Study Algorithms
Vložit
- čas přidán 23. 07. 2024
- To see more videos like this, you can buy me a coffee: www.buymeacoffee.com/studyalg...
A very important and an interesting problem that will assess your logical thinking skills. From an array find the product of all other elements except self. Watch this video to understand why the most obvious way to approach this problem will give you a wrong answer, and how can you come up with an efficient solution. Follow along with animations, visual aids and a dry-run of code in JAVA
Chapters:
00:00 - Intro
00:50 - Problem Statement and Test cases
03:05 - The most obvious way fails
06:33 - Thinking out of the box
10:55 - Dry-run of Code
12:57 - Final Thoughts
Actual problem on LeetCode: leetcode.com/problems/product...
📚 Links to topics I talk about in the video:
LeetCode Problems: • Leetcode Solutions
Problems on Arrays: • Arrays
What is Big O?: • Big O Notation Simplif...
Other medium difficulty problems: • Medium Problems
📘 A text based explanation is available at: studyalgorithms.com
Code on Github: github.com/nikoo28/java-solut...
Test-cases on Github: github.com/nikoo28/java-solut...
📖 Reference Books:
Starting Learn to Code: amzn.to/3sJm8Wl
Favorite book to understand algorithms: amzn.to/4848xJH
Favorite book for data structures: amzn.to/3P96YBv
Get started for interview preparation: amzn.to/44Nn5du
🎥 My Recording Gear:
Recording Light: amzn.to/3PdsViT
Microphone: amzn.to/3Exv83x
Recording Camera: amzn.to/3PwyN8e
Tablet to sketch and draw: amzn.to/3ZdKVy7
Sketching Tool: amzn.to/45XJEgY
Laptop to edit videos: amzn.to/460ofDu
💻 Get Social 💻
Follow on Facebook at: / studyalgos
Follow on Twitter at: / studyalgorithms
Follow on Tumblr at: / studyalgos
Subscribe to RSS feeds: studyalgorithms.com/feed/
Join fan mail: eepurl.com/g9Dadv
#leetcode #programming #interview
Next level teaching sir !! You are literally a hidden gem!!
glad you feel that way
thanks for the lucid explanation , you're a hidden gem :) , you deserve way more subscribers
Your explanation is so clear! I like how you draw out everything to explain it! Thank you
The drawing really helps a lot 😄
Really good explanation. Clearly understood the concept. Thank you!
Thank you a lot for such great explanation of the problems!
Excellent explanation. I am so glad that I came across your YT channel
Thank you so much for explaining each line in a very simple manner.
recently found your videos, and im loving the explanations. thank you !
hope they are of help to you
Wow, that is such a clear soln, thanks!
Very nice explanation, I really search your channel for Ds-algo questions . Thanks sir for teaching free.
Totally understood. Thanks a lot.
Nicely explained. Thank you very much
Thank you so much sir.
Explained very well.
like always your explanation and video quality is awesome. i will try to share your videos as much as possible .
So nice of you
Awesome explanation 🎉
THANK YOU , I TRIED VERY HARD BUT COULD NOT SOLVED. YOU CLEARED IT IN A MIN .❤❤❤❤❤❤
Good video, very easy to understand.
Sir Best Explanation!!
I was stuck in neetcode and i thought it would be impossible. After seeing your video, i understood clearly
thanks for your feedback and support :)
OMG , same happened to me 🤣🤣🤣🤣
@@mustafahassan9383😊
same happened to me returns..
Same
Fall in love with your explanation ❤❤❤❤❤❤❤❤
Amazing explanation!
I like your way of explaining the problem , with this i learnt to solve problems and as well as the way of explaining the code to others.
It helped me a lot in my interview.Thank you so much.
I try to approach the problem in a way as you would do in an interview. Glad it helps :)
Recently found your channel, whenever I don't understand neetcode solutions I come here. Thank you sir!
@neetcode is also an amazing channel :)
Same!
Very nice explanation.
Great teacher 👏
Amazing Explaination
Hi Sir,
Eveytime I am searching for a leeetcode problem, I add your name in the suffix hoping you have done a video on it. I have understood each and every video that I have watched. Please do solve all the problems, that will be very helpful for people like me.
Man you are god 😭🙏 your explanation is outstanding 👏 you earned a subscriber today ❤️.
Keep going Nikhil, I was stuck and I was about to give up too. I feel taught today
glad that was helpful
Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
Thanks bhai
leetcode ke videos banate raho mere liye or sabke liye
Love you bro
Thanks for the love
Here our space complexity can be reduced to O(1)..overall nice explanation
Thanks a lot....you are great....
I usually don't comment but this kind of video I see my hands automatically goes in comment section for comment.
Thanks Nikhil you even demystified how dividing will give results, most of people don't know how dividing is giving the answer and thanks for explain postfix and prefix in detail.
u are the best! thx! ❤👏✨
you are the best
you explained it very well. thanks
So nice of you
Thank you
i have shared your tutorials to my friends
Thank you so so much 😄
Nicest explanation ❤❤
Thank you bro❤❤
thank you
Leetcode has mentioned to try O(1) space solution. You should add one more part in the video for such optimizations.
you are great :)
amazinggggggg
Excellent explanation.
Glad you liked it
thanks
Thanks
superb
great
Bhaiya why would you used num[i-1] and [n+1] in both the left and right Loop pls explain
please try to look at the explanation of the left and right array once again, we have to skip those elements. if you are still confused..let me know
The way you teach it feels like there is nothing in DSA
Thanks for the appreciation…I really try to simplify things as much as possible.
Sir the question also says You must write an algorithm that runs in O(n) time and without using the division operation.
I don't use the division operator.
Thank you for the video. But somehow I don't know how it's possible to find the solution without knowing this trick (prefix, suffix). What am I missing in my reasoning?
This is a kind pf problem which comes with practice. The idea is that once you solve a problem like this, it will open your mind and you will try to apply the same pattern to future problems.
You r osm 🔥
Thank you so much 😀
Here is my solution in python, i used to for loop and it givs the same answer.
arr=[2,1,3,4]
arr1=[]
r=1
for i in range(len(arr)):
pro=arr[i]
for j in arr:
if j is not pro:
r=r*j
arr1.append(r)
r=1
print(arr1)
but the time complexity of your solution is O(n^2)...because of the nested loops. You can try to improve that.
@@nikoo28 this will fail when arr = [0,0]
@@avanishraj386 did you try the code given on github? It will work with your sample test case. What error are you getting?
@@nikoo28 I am not talking about your code, I have replied the above comment of "True Coding".
it gives the following error for the array you created to store right side value.
error: cannot find symbol [in __Driver__.java]
int[] ret = new Solution().productExceptSelf(param_1);
^
symbol: class Solution
location: class __DriverSolution__
Check the github link in the description below, for a working code :)
i was getting time limit exceeded for one of the test cases.
Check out the code given in video description
Sir i didn't understand the approach that you have explained about 2^32 and 10^12>2^32
What part are you getting confused with?
brackets are not allowed here; to declare an array, place the brackets after the name
int[] left = new int[nums.size()];
~~ ^
[]
this error is coming
Please recheck your code. The declaration is correct. Also check my complete code in the github link available in video description.
@@nikoo28 yes sir I have corrected it ..I haven't made left and right as vectors! Thanks for the solution ! 😄
but we have to solve this with O(1) space
let me come back to you.
Question says no extra space, then why left and right arrays
That part got added to the question recently. It wasn't there when I created the video. Will post an update soon on it.
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# Check if the input list is empty
if not nums:
return []
length_of_nums = len(nums)
# Initialize the result list with 1s
result = [1] * length_of_nums
product = 1
# Calculate the product of all elements to the left of each element
for index in range(length_of_nums):
result[index] = product # Store the product of elements to the left
product *= nums[index] # Update the product for the next element
product = 1
# Calculate the product of all elements to the right of each element
for index in range(length_of_nums - 1, -1, -1):
result[index] *= product # Multiply by the product of elements to the right
product *= nums[index] # Update the product for the next element
return result
i think this is good approach then your code please review it
solving in O(n) time and o(1) space complexity
class Solution {
public:
vector productExceptSelf(vector& nums) {
int zero = 0;
int tmul = 1;
for(auto num : nums){
if(num)
tmul *= num;
else{
if(zero){
tmul = 0;
break;
}
zero++;
}
}
for(auto &num : nums){
if(num)
num = zero>0 ? 0 : tmul/num;
else num = tmul;
}
return nums;
}
};
bro this problem has a better and more simple solution
step 1 - just calculate the product of the whole array in this example the answer would be 1*2*3*4=24
step 2 - in the second step to calculate result [ i ] just divide the calculated result by nums [ i ] e.g to calculate result [ 0 ] = 24/1 =24
result [ 1 ] =24/2 =12 and so on
does this method get accepted? I believe you will hit limits when trying to multiply all the numbers.
I am dumb