Perfect Squares - Dynamic Programming - Leetcode 279 - Python

  Рет қаралды 56,983

NeetCode

NeetCode

Күн бұрын

Пікірлер: 54
@edwardteach2
@edwardteach2 3 жыл бұрын
I ended up getting a time limit exceeded for the input: 3288
@hoyinli7462
@hoyinli7462 3 жыл бұрын
same here
@NeetCode
@NeetCode 3 жыл бұрын
Hey thanks for bringing it to my attention. I think this is just leetcode being dumb... I replaced the line where i call the min() function with an if-statement and it passed on leetcode. This is the code i used: class Solution: def numSquares(self, n: int) -> int: cache = [n] * (n + 1) cache[0] = 0 for i in range(1, n + 1): for s in range(1, i + 1): square = s * s if i - square < 0: break if 1 + cache[i - square] < cache[i]: cache[i] = 1 + cache[i - square] return cache[n]
@aparnaaketi1616
@aparnaaketi1616 3 жыл бұрын
@@NeetCode I got time limit exceeded for input 8405 even after using the if statement
@王雅璇-b7y
@王雅璇-b7y 2 жыл бұрын
@@aparnaaketi1616 same to me
@michaelscotto4009
@michaelscotto4009 2 жыл бұрын
The reason getting time limit exceeded is that we need to loop through perfect squares in the inner loop only. Add this at the top and use for inner loop: squares = [x**2 for x in range(0, n) if x**2
@andreipoehlmann913
@andreipoehlmann913 3 жыл бұрын
It still blows mind to see such simple bottom-up DP implementations. Even though I've been practicing for weeks.
@JackJackson-ho5bv
@JackJackson-ho5bv 3 жыл бұрын
Thanks for the video! It's so much better than all the other videos explaining this problem that I've seen so far on KZbin.
@NeetCode
@NeetCode 3 жыл бұрын
💡 DP Playlist: kzbin.info/www/bejne/bWTVZH6Nnqqpr80
@dmitrydmitriev2554
@dmitrydmitriev2554 Жыл бұрын
dp = [n] * (n+1) - nice move to fill dp array with maximum values. Thank you!
@sunnilabeouf
@sunnilabeouf 3 жыл бұрын
goated, your videos along with alvin's dynamic programming course have made dp problems soooo much easier for me
@programming1734
@programming1734 3 жыл бұрын
Alvin? Can you share the playlist or channel
@sunnilabeouf
@sunnilabeouf 3 жыл бұрын
@@programming1734 heres the video! kzbin.info/www/bejne/pXPXZmaPl7dsgc0 it starts off really simple and works up how to come up with a recursive brute force algo, then memoize it and turn it into a dp solution
@programming1734
@programming1734 3 жыл бұрын
Thank you @abdulrahman Tolba
@balaganesh5484
@balaganesh5484 3 жыл бұрын
No time limit exceeded. Same concept: instead of checking minimal of target with all availble squares, here reaching to n with minimum squares with 1 after another. def numSquares(self, n: int) -> int: if(n
@vincentwang5887
@vincentwang5887 2 жыл бұрын
Fan here. We can also utilize Lagrange's four-square theorem to solve this question. class Solution: def numSquares(self, n: int) -> int: def isPerfectSquare(x): y=int(x**0.5) return y*y==x def isFourSqaure(x): while x%4 == 0: x/=4 return x%8==7 if isPerfectSquare(n): return 1 if isFourSqaure(n): return 4 i = 1 while i*i
@kxf8608
@kxf8608 2 жыл бұрын
This is absolutly savage!
@albertgracelieu1506
@albertgracelieu1506 3 жыл бұрын
@NeetCode Interestingly enough, this DP method is even slower than brute force and leads to TLE. Did I get anything wrong here? Have you encountered TLE when submitting this answer?
@333jjjjjj
@333jjjjjj 3 жыл бұрын
I did not watch the whole video; the only hint I needed was the similarity to coin change (though I'm facepalming for not recognizing it on my own.) I coded a bottom-up DP solution that easily ran within the time limit. Edit: I watched it and the only real difference is that i computed the set of squares i needed as an array once at the beginning.
@zishiwu7757
@zishiwu7757 2 жыл бұрын
Not this answer, but when I pre-computed all the squares that are less than n, and iterated those in the inner for loop, I got TLE. Then I tried NeetCode’s solution in the video and got runtime of ~6900ms or faster than 13% of Python3 solutions. Then I tried NeetCode’s solution but using C++ and runtime shrank to 257ms which is faster than 42% of C++ solutions. I wonder if for this problem, LeetCode’s time limit is more harsh for Python3 than for C++. But I don’t think you should worry about what LeetCode says. If you can ask clarifying questions, propose and explain a correct solution clearly to the interviewer, and implement it - well that’s what really counts on the interview.
@vivekgupta707
@vivekgupta707 4 ай бұрын
Thanks for the video !!! Really helped to understand the recurrence relation
@atharvakulkarni3007
@atharvakulkarni3007 3 жыл бұрын
We can also do this using Unbounded Knapsack?
@sidhartheleswarapu
@sidhartheleswarapu 8 ай бұрын
For all DP problems, should I always start with a decision tree in order to know how to approach it?
@name_surname_1337
@name_surname_1337 11 ай бұрын
precomputation is 20 times (real number) faster. The js runtime estimation is very random, but anyway, this solution is very slow. It's much faster to calculate all squares in advance
@studyaccount794
@studyaccount794 2 жыл бұрын
There's also a bfs based approach to this problem. I think the TC will be the same. Only one extra queue is required. Still the space complexity will be O(n) ig. class Solution { public int numSquares(int n) { Queue q = new LinkedList(); //add visited array so we don't go to values which we have traversed already (similar to dp) HashSet visited = new HashSet(); int ans = 0; q.offer(n); while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i
@rkalyankumar
@rkalyankumar 2 жыл бұрын
This can also be solved using BFS. Can you please do a video of this problem solving using BFS?
@numberonep5404
@numberonep5404 2 жыл бұрын
As is, this code is O(n^2), it lacks the square root, but otherwise nice video :) ! I love your thumnails btw they really make the videos enticing and easy to click at imo!
@zishiwu7757
@zishiwu7757 2 жыл бұрын
Why do you think NeetCode’s solution is O(n^2)? In the inner loop, it breaks as soon as we get a square > target. So we never evaluate more than sqrt(target) number of squares, which is bounded by sqrt(n), in each iteration of the inner loop. So I think NeetCode is correct saying his solution is O(n*sqrt(n)).
@numberonep5404
@numberonep5404 2 жыл бұрын
@@zishiwu7757 my baaad ! you are right indeed definitely O(n*sqrt(n))
@adityagoyal9556
@adityagoyal9556 4 ай бұрын
def numSquares(self, n): return self.num(n,{}) def num(self, n,dic): if(n in dic): return dic[n] arr = [] frequency = int(math.sqrt(n)) for i in range(frequency): i+=1 arr.append(i) maxCount = -1 for i in arr: count = self.num(n-(i*i),dic) # the argument is >=0 since i*i
@kx01
@kx01 3 жыл бұрын
This is similar to coin change problem. in coins we will have 1,4,9,... sqrt(n). amount will be n;
@varunshrivastava2706
@varunshrivastava2706 2 жыл бұрын
Sort of
@souparnomajumder
@souparnomajumder 2 жыл бұрын
This code will give TLE, as -> for s in range(1, target +1) will get the loop to run 1 extra time, to hit the condition if s*s > target: break, ex: if target is 5, the loop will run for 1, 2, 3 and then break, changing the loop to -> for s in range(1, int(sqrt(target)) + 1): will pass all the tests, as the 2nd loop for a target of 5 will run only for [1, 2]
@forresthu6204
@forresthu6204 2 жыл бұрын
import queue class Solution: def numSquares(self, n: int) -> int: # Breadth first search for solution, timed out at input 7168 Q=queue.Queue() Q.put((n,0)) while Q: currentValue, currentLevel = Q.get() start =1 while start*start
@Kaviarasu_NS
@Kaviarasu_NS 9 ай бұрын
I just came across this below solution Perfect Squares on leetcode, can you teach us how its solved using deque class Solution: def numSquares(self, n: int) -> int: queue = deque([n]) ans = 0 while queue: ans +=1 for _ in range(len(queue)): cur = queue.popleft() j = 1 while cur-j*j >= 0: if not cur-j*j: return ans queue.append(cur-j*j) j+=1 return ans
@ningzedai9052
@ningzedai9052 2 жыл бұрын
This is graph problem that looking for the shortest path by BFS. If you think it in this way, it will become an very easy problem.
@smonkey001
@smonkey001 3 жыл бұрын
Best explanation on KZbin you rock sir!
@lettry5297
@lettry5297 3 жыл бұрын
Hi., thanks for making this video Can you please cover this problem - Shortest subarray with sum atleast k (leetcode-862)
@CS_n00b
@CS_n00b 4 ай бұрын
so basically coin change?
@veliea5160
@veliea5160 3 жыл бұрын
dp[target]=min(dp[target],1+dp[target-square]) Can somebody please explain this. I did not understant :(
@artemchaika
@artemchaika 2 жыл бұрын
we want to store the minimum amount of squares required to get to dp[target], let's say it's 7, so we iterate up to 7, for example we take 1, and see if 7 - 1*1 >= 0, so it's 6, and we want to check if the amount of squares required to get to 6 + 1 (cause we already substracted one square 1*1) is less then the previous amount we stored for 7. So as a result we will have the minimum to get to 7 stored there, which can be used by the following bigger values, the same way we used the minimum for 6, which was stored before etc.
@veliea5160
@veliea5160 2 жыл бұрын
@@artemchaika we are calculating `dp[target` which is unknown yet. How come this equation work: `dp[target]=min(dp[target],1+dp[target-square])`. on the right side we still have `dp[target`
@sabrish7263
@sabrish7263 3 жыл бұрын
Hi, is it more like the coin change problem ?
@sachinchhipa6222
@sachinchhipa6222 3 жыл бұрын
Go for more inf.,below link kzbin.info/www/bejne/gpqXlmaGg9t0r7c
@aaroldaaroldson708
@aaroldaaroldson708 9 ай бұрын
as usual seems like an easy tutorial, but I didn’t get s*it
@MHDNOUR-i4f
@MHDNOUR-i4f 9 ай бұрын
is this way called backtracking
@almaguerrero3041
@almaguerrero3041 9 ай бұрын
esta bien perro alv
@hoyinli7462
@hoyinli7462 3 жыл бұрын
but your ans doesn't pass all the test cases
@NeetCode
@NeetCode 3 жыл бұрын
Thanks for bringing it to my attention. Please see the pinned comment and let me know if it passes.
@Eggleweb97
@Eggleweb97 2 жыл бұрын
it passed all test cases,check again
Edit Distance - Dynamic Programming - Leetcode 72 - Python
21:00
ЛУЧШИЙ ФОКУС + секрет! #shorts
00:12
Роман Magic
Рет қаралды 22 МЛН
Will A Basketball Boat Hold My Weight?
00:30
MrBeast
Рет қаралды 141 МЛН
Mastering Dynamic Programming - How to solve any interview problem (Part 1)
19:41
Open the Lock - Leetcode 752 - Python
14:22
NeetCode
Рет қаралды 40 М.
Ones and Zeroes - Leetcode 474 - Python
17:59
NeetCodeIO
Рет қаралды 11 М.
Maximal Square - Top Down Memoization - Leetcode 221
19:50
NeetCode
Рет қаралды 70 М.
LeetCode was HARD until I Learned these 15 Patterns
13:00
Ashish Pratap Singh
Рет қаралды 525 М.
Climbing Stairs - Dynamic Programming - Leetcode 70 - Python
18:08
Zendesk Mega Backdoor
36:43
ThePrimeTime
Рет қаралды 76 М.
This Single Rule Underpins All Of Physics
32:44
Veritasium
Рет қаралды 4,1 МЛН
ЛУЧШИЙ ФОКУС + секрет! #shorts
00:12
Роман Magic
Рет қаралды 22 МЛН