Mods can we sticky the Blind 75 onto the sidebar or maybe add a post on "where to begin with Leetcode if you're studying for interviews?"
I never heard that FANG companies prefer one DP over another.
You can use what DP approach you are comfortable with.
The more important thing is the explanation of your solution.
You can practice iterative dp on buy and sell series of puzzles.
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Also for understanding it, I think it's not that much different than the recursive one.
You have to figure out the key variables for the current state dp[i], dp[i][j] and afterwards decide the recursive step or the transitions to a previous already calculated states.
I think the best way to think about it is by assumption.
To figure out the transitions you assume that the previous states are already calculated, and you only care about the current one.
In recursion for example you are sure that you have them because you will recalculate it if they are not yet calculated.
In iterative approach you are going bottom up, and you have to be sure to calculate all the states even if they are not used in the future.
Also the base case is more complicated in iterative approach for example for 2D dp solutions.
But I think you can get used to the patterns if you practice it.
I had the same question for https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/
the top down is a lot easier to make sense of and this is a common amzn problem
hope someone answers
I’d suggest reading the topcoder dp tutorial first. After that you can try solving questions from this link DP beginner problems
You're describing the Levenshtein distance algorithm I believe.
You can either do:
It is a DP Hard problem and I only know how to do a bottom-up version, but basically, you build a 2D array and tabulate how many calculations it would take to turn one string into another.
You'd do a nested for loop as you would with most DP problems, with the outer for loop iterating through the first string, and the inner iterating through the second string, but also including the base case of two empty characters at index dp[0][0] (if you had two empty strings, the distance would be zero).
In each iteration, you would make the following subproblem choices:
If the two characters of each string that you are comparing are the same, you can grab the distance that was calculated at the top-left of the current cell, because that is the distance of the two substrings with that character subtracted.
Otherwise, you would take the minimum value between the following options and add one to it to include your current index:
The key for those options would be:
​
Replace | Insert |
---|---|
Delete | Current Cell |
​
A tabulation for your example would look like this, you can follow along using the options above.
"" | l | o | k | |
---|---|---|---|---|
"" | 0 |
1 |
2 |
3 |
l | 1 |
0 |
1 |
2 |
o | 2 |
1 |
0 |
1 |
o | 3 |
2 |
1 |
1 |
k | 4 |
3 |
2 |
1 |
As every bottom-up DP problem goes, the answer is in the last cell of the array, one. This makes sense because you would need to add an "o" for "lok" to become "look".
Here is the LeetCode problem, https://leetcode.com/problems/edit-distance/.
If you refresh the page and click on the "Accepted" link then it will show the distribution that your solution is in, there you can compare your solution with others.
It is possible that your solution missed the point of the question like this guy.
First and the main reason is that doing topicwise questions though a little easier, creates a sort of bias in your thinking because you know that the question is based on some topic. The top 100 or must-do lists kind of are mixed topic as well as have a good chance of coming in the interviews ( or some variant).r. This gave me more confidence and was much more helpful in tough topics for me like graphs.
Another one was to follow a topicwise question list. I followed this link, this contains a lot of useful posts especially when practising topic wise. In case I got stuck on some topic and weren't able to do any questions, I just sorted the topic on leetcode with acceptance rate and started doing it in that order. This gave me more confidence and were much more helpful in tough topics for me like graphs.
​
Also one more thing to keep in mind is that there is no correct way or a way to do interview prep, if there had been one everyone would have followed that. Try different ways and see if things seem easier if you do one way.
​
​
P.s: I mixed the two strategies because of mainly two reasons,
First and the main reason is that doing topicwise questions though a little easier, creates a sort of bias in your thinking because you know that the question is based on some topic. The top 100 or must do lists kind of are mixed topic as well as have a good chance of coming in the interviews ( or some variant).
Second, you will see that a lot of these top-100 , must-do lists have lots of questions in common. I did all those questions again even if I did them previously, as since those questions are probably more important than others. This helped me to really have a grip on some tough questions and patterns.
You need to begin with some structure. The LeetCode lessons are great for this. Go to https://leetcode.com/explore/learn/ and start with familiar topics there. This will make your progress more linear, less random, and give you a sense of why you use the patterns needed for a given question.
Not an expert on Union Find by any means since the Sinking Islands approach on this problem is so intuitive but have you tried the code in this link?
Check out leetcode's top easy interview questions collection. Pretty much covers most of what you should know. Then move on to the medium collection. - https://leetcode.com/explore/featured/card/top-interview-questions-easy/
I think Python Tutor will be helpful here. Despite having Python in the name it has support for - - Python - Java - C - C++ - JavaScript - TypeScript - Ruby
Appreciate it. I have the discussions and the solutions to look at. I just keep running into BST problems that I get lost in the recursion. Last problem I had trouble on was https://leetcode.com/problems/recover-binary-search-tree/description/. Was looking for general advice on these problems rather than help on any in particular
Edit: I found a solution but I continued to run into more edge cases as I tried to submit and my code became an unworkable mess
>I'm a year late lol but I'm also looking for discounts and found this post, figured I'd share my findings here, they have a 15% discount
>
>https://leetcode.com/subscribe/?ref=KqSTb9jy
This is great, thanks! I wonder if they're going to do a bigger discount like they've been doing for the past couple of years. Last year I got a subscription for $111. Any thoughts?
> "how to tackle problem?"
specifically for the linked-list cycle problem,
you just need to know the "fast and slow iterators pattern" (two pointers, one moving 2 nodes at a time, the other pointer moving 1 node at a time; if there's a cycle the two will eventually overlap)
​
perhaps proving that the two pointers will eventually overlap would require math
​
but usually you're just expected to know the patterns and when to employ them (what im writing focuses on the patterns)
​
---
​
that said there are a good number questions on leetcode that require you to form proofs in order to solve them efficiently
​
one such problem i attempted ( couldn't come up with the proof unfortunately, had to read the discussion for the proof :] ) recently = https://leetcode.com/problems/repeated-string-match/
NP!
They will want to see you implement binary search.
As for learning TreeMap, it's useful when you want to be able to PUT and GET in sub-linear time.
Here's another problem that can elegantly be solved using TreeSet https://leetcode.com/problems/contains-duplicate-iii/
my friend took this assessment last month and he got one easy and one medium (https://leetcode.com/problems/robot-return-to-origin/) leetcode questions. He is a bootcamp grad, he was probably graded as SDE1. I was very surprised he got a medium one.
I just did the q myself and noticed using a memoized backtracking approach was faster than regular 0/1 knapsack actually. Like 3500ms to sub 100 ms (in python). This is a 2^n solution (n = length of list), but it's faster than the n*W (where W = sum of all the nums /2). I'm still a big noob at DP, need to practice way more to get used to the patterns.
Also check out this q https://leetcode.com/problems/partition-to-k-equal-sum-subsets/
It's a deceptively similar but you can't really use the same approach!
I think you're asking about this problem right ->Count of Smaller Numbers After Self - LeetCode. This is basically to calculate the number of inversions in an array. An inversion in an array exists iff A[i] > A[j] and j > i. It's a pretty famous problem and it can be solved by modifying the merge function of the merge sort algo.
Edit:
For stack based problems, NGR, NGL, NSL, NSR are pretty important (NGR is basically Next Greater to Right, NGL is for Next greater to left). If you are comfortable with these and understand on where to apply these, then most of the stack qns are pretty straightforward (tho there are some qns which are very tough as well)
Just change the way you think about not being able to do a question.......
Whenever I am not able to do a medium, there's always a trick or technique that I have never seen before.
When I get stuck on the medium, I am elated instead of getting depressed and mad. I will be happy because I know I will be learning a new technique I have never seen before. Have a hunger to learn.
Some tricks they use to convert O(n^2) to O(n) in medium is like how do you even think of this. Impossible.. Like how. For instance this question can be solved in O(n).
Hey Rectudid,
This problems sounds very similar to a problem that showed up in the contests a few weeks ago. It was a medium but I remember it feeling more like a hard. https://leetcode.com/problems/maximum-subarray-min-product/
This is not a sliding window problem, but it can be done in linear time. The basic idea is to visit each element in the array, and find the subarray for which it is a minimum value. This means that you need to know the location of the next smaller elements to the left and right.
Keeping track of the smaller elements can be done using a technique that I call "monostack", although I don't think it's a common name. You use a stack and impose the constraint that the stack is always decreasing (or always increasing depending the left or right side). This enables you to quickly find the last smaller value, without doing a linear search.
Checkout the solutions to the problem I linked, it uses the same approach you can use to solve this error rate problem.
some mediums should be hards and some hards should be mediums..
this one https://leetcode.com/problems/integer-to-english-words/ takes a lot of verbose code but it seems like it should be an easy.
The number of leetcode questions was overwhelming when I started. Then I found the Blind 75 list (https://leetcode.com/discuss/general-discussion/460599/blind-75-leetcode-questions), which has good coverage of different topics.
Strangely, I was thinking about this yesterday and googled this:
Leetcode FullTime employees time management
According to those replies, they all started waking between 5-6 AM and following a strict time table. This seems impossible for me. I hope somebody has a better time table.
Just do this list: https://leetcode.com/problemset/top-100-liked-questions/
You shouldn't bank on getting a question you've seen before, that'll bite you later.
Whilst many of the easy questions are trivial, some are actually more challenging, and have taught me new things still (e.g. 405. Convert a Number to Hexadecimal taught me two's complement of -1 is UINT_MAX - it was one of the few questions that I've had to use unsigned integers for).
My credibility is that I have been running the daily coding collaborative problem solving since may 2020. I have now recorded over 250+ live coding session Zoom calls. My telegram group has over 400 active developers. I have refined the problem solving process over a period of 2 years.
It differs from all other books because none of them are teaching you the analytical reasoning, patterns of reasoning and critical thinking needed to solve coding problems. No one will give you 100% money back guarantee. I believe in the quality of my product and offer 100% money back guarantee.
I am also the author TDD book published by Apress in 2017: https://www.amazon.com/Test-Driven-Development-Ruby-Introduction-ebook/dp/B06XPBWNL6/
I’m a huge fan of this book, the examples are in JavaScript, python, and ruby, but if you know one you’ll be able to follow them all. This book has helped me a lot. I recommend after you finish the section you go on leetcode and tackle some easy problems and later on some mediums
https://www.amazon.com/Common-Sense-Guide-Structures-Algorithms-Second/dp/1680507222
The reason you find DP hard is because you lack the mathematical foundations. I highly recommend reading: manber After which DP will become much simpler for you to grasp.
https://en.wikipedia.org/wiki/Argument_from_authority - a well-known logical fallacy. I suggest you pick this book up and educate yourself on logical fallacies - https://www.amazon.com/Illustrated-Book-Bad-Arguments-ebook/dp/B00M9P7JKI.
As for your particular objection, yes, there are plenty of examples of things worked on by thousands (or millions) of people which make no sense - the scores of "failed" Google projects (Google Wave, Google Code, Google Plus, and now Carbon), the Metaverse, the original AI projects (SHRDLU et al) leading to the original AI winter, Blockchain et al. Too many to list actually.
The things is this - it's a logical issue. Unless one can develop a sentient program (you know, the original idea of AI, not the Compute-based "AI" (deliberately quoted)) that can interact with the customer to get, refine, and update requirements, implement prototypes, write tests and weed out bugs, iterate over features in sprints, work on production issues, and deliver products that satisfy said customer requirements, then it's mind-numbingly obvious that the human element can never be eliminated, or indeed minimised to the extent that it has in certain other industries (manufacturing, for instance).
Good luck even beginning to try defining what "intelligence" or "conscious" is, let alone implementing it. Modern "AI" is fundamentally the same (well, less rich in fact) as it was half a century ago - it's only the computing power that has increased exponentially, but this has its own fixed limits. My personal conjecture is that there is not enough compute in the universe to be able to create a digital analogue (pun intended) of the human consciousness.
Use the Feynman approach after each question. If you can't explain/justify your choices to a 5 year old, then you don't understand it. After each question, I did a COE. The COE looks something like this:
This is my most recent COE: https://www.notion.so/Rearrange-String-k-Distance-Apart-158773966f2841c69995c7df8b843c9a
I've made a small curation that might help you, You can also reach out to me via Instagram if you need any further help
https://www.notion.so/dhruvindave/Bookmarks-04aee8d928c04fe19d34fb6bc2fb8ac9
Become comfortable with the language first by solving easy exercises and exploring its capabilities. No need to rush. Understand the standard library, its built-in data structures, how to use them, etc. Learning to write an essay without understanding the grammar & language primitives well doesn't make sense, does it?
Implementation is also a problem to solve, so don't assume that if you are able to come up with a logical solution, you can code it right away. Also, programming is like swimming, you can't learn by analyzing how to do it, and just be great at it when you do it. Give it some time, you'll develop an aptitude for it.
From a spiritual point of view, whenever you feel frustrated, try to forget these feelings, with time they should reduce. The more you pay attention to them and react, the more these feelings are gonna increase. That's the main key idea behind vipassana - not reacting to feelings of craving and aversion, and understanding they are impermanent. Listen to the lectures on this app. He explains what I said in more detail.
> Any suggestions and resources on how to improve in CP. Like I'm decent on DSA part but my observational skills and maths is very weak for CP.
For math part, combinatorics is very important in competitive programming especially for dp related problems. This book helped me so much! I solved every single problem in this book by hand! Awesome book.
And I will edit this reply and add more resources later as I am busy now :)
I bought this cheap camera.
https://www.amazon.com/OKIOCAM-Documents-Recording-Time-Lapse-Definition/dp/B0827LLG8P/
Cons: It's turned on all the time when it's plugged in. And one customer review claims that it's calling back to China (which I haven't bothered to confirm). Its construction is also very flimsy in nature.
Pros: But it works perfectly fine for my mock technical interviews (on Pramp). I just need to flip the camera. And press a physical button on the camera to flip the image. The resolution is high enough that I can just use a piece of paper, or a small whiteboard. And when my diagram is done, I can just flip the camera back to my face, press a button, and presto (and no, I would never use such a camera for real work where trade secrets are important, and I always keep the camera unplugged otherwise). But being unemployed, the price of such a camera really can't be beat.
Another thing I considered buying is a cheap usb Wacom knockoff, but if I were to interview on Google Docs, I don't know how well that would work. If anyone has tried that approach, please let us know if drawing with a tablet on a Google Docs would actually work. Those are also in the $30 to $50 price range.
Generally, if searching for an algorithm or data structure results in mainly hard questions coming up, then it's usually unlikely for them to be needed in interviews.
If you've already done a good chunk of easy/med/hard of the categories I mentioned, blind 75, etc., then it's always fun to go into more niche stuff, but of course they payoffs will be more and more for a hobby over time. The people on CodeForces study things that are going to be way out of scope for most interviews, and will have much better advice for advanced topics than me (geometry, advanced graph, advanced dp, advanced math, etc.)
I think this is the exact question you’re referring to
https://leetcode.com/problems/minimum-moves-to-equal-array-elements/description/
The description is a bit different than what we just worked on. In this leetcode problem, you can increment up to n-1 elements of the entire array as one “move”.
Look at the discussion for solutions. Good luck
That's a fun problem. Yeah, it's pretty much just another example of the difficulty system being completely broken. Adding 2 linked lists is considered the same difficulty as this!
That's true. It's typically better to start from top down and then translate the recurrence relation to bottom up. I wish he took that approach more often.
I won't speak to every one of his videos, just that the Discussion for 1143 Longest Common Subsequence just wasn't hitting for me, in terms of how/why they were using the matrix. So many were just code, and no walk through.
Even the top C++ solution from votrubac just kinda stated what the code did, but I didn't get the why. The third reply in that thread was a suggestion for Tushar's video.
Tushar stepping through the table and walking through the decisions being made made the Discussion solutions click (at least the bottom up)
I mostly use C++, so Tushar's Java is pretty clear. I tend to skip Python Discussions.
Don't get me wrong, the Discussions are absolute gold and where I start when I need help. But sometimes a human walk through really helps.
I'm a big fan of Abdul Bari, neetcode, TECH DOSE, Tushar Roy, Back to Back SWE (though his constant shouting can be exhausting), and Nick White (though he can be condescending).
Yeah. I used that link to help introduce the concept of reading the leetcode discussion board. I like the one above because it includes the concept of graph, interval, and string dp being studied separately, which I liked.
This is how I find problem lists from people who have done way more than I have.
For me this one medium is really nice, https://leetcode.com/problems/design-add-and-search-words-data-structure/description/ It mixes 2 advanced concepts, could easily be hard. The one with max rectangle is cool too, it's similar to another one with max temperatures if I remember correctly 😀
https://leetcode.com/problemset/database/
I don't know if you know about this, but this is as good practice as any for learning basic SQL. It'd probably only take like 20 problems to have the basic syntax down.
Learning != giving up. The people who are top voted on most answers, e.g.
are so insanely good at this that "normal" studying methods probably don't apply to them any more. Consider the people who get into Big N companies with only the Blind 75. That's literally nothing compared to what people who are S tier at this are doing with their thousands of problems practiced lol. Don't compare yourself to them, but do learn from them, because they are needlessly fantastic at this.
https://leetcode.com/discuss/general-discussion/460599/blind-75-leetcode-questions
This is how I started getting good at mediums. Basically, filtering by topic is super useful for learning a new topic.
Obviously, if you're top tier, then you can switch between the 2 freely, but I pick top down due to the explicit base cases in the form of "if" statements and the ability to use "@cache" on python methods. The meat of the code, e.g. ans = dp(dp(i - 1) + dp(i - 2)), tends to be one of the base problems in lists like
https://leetcode.com/discuss/study-guide/458695/dynamic-programming-patterns
https://leetcode.com/discuss/general-discussion/460599/blind-75-leetcode-questions
This is good. Just look at the answers if you don't get the question at first.
There's almost no YT sources I'd recommend, unfortunately. Even people like Tushar Roy and stuff aren't that useful compared to just looking at official answers/highly upvoted discussion answers IMO.
You and me both.
Once you are familiar with how a data structure, e.g. an array, works, you probably shouldn't sort by data structure any more.
To get good at something like 2 pointers, I filter exclusively by 2 pointers, and then do exclusively 2 pointer problems. When finding problems to practice, always glance at the solution of the problem before you start, because a lot of problems are a waste of time. e.g., you'll want to practice 2 pointers, but it's actually a hard dynamic programming problem. The best 2 pointer problems on LC always have "2 pointer" in the title of the solution, e.g.
https://leetcode.com/problems/valid-palindrome/
Following the order of something like the blind 75 or something helps a lot, because they try to separate topics by complexity. For example, you should be good at 2 pointer before you try dynamic programming, because a lot of dynamic programming problems involve 2 pointers. Study 1 topic at a time.
Here's the topics I studied in order.
sliding window
two pointers
prefix sum
binary search
monotonic stack
monotonic queue
​
matrix
tree
types of graphs:
- matrix
- binary tree
- binary search tree
- n tree
- graph
for each graph:
bfs/dfs
dijkstras
topological sort
backtracking
(implement recursively like backtracking)
dynamic programming
greedy
string
hash function/rolling hash
Yes
On the bottom of the question, you can click on "related topics", and see .. the related topics (who would've thought!)
this is the list of graph tagged questions : https://leetcode.com/tag/graph/
Made a list out of this digging very deep into the post got a total of 46 problems this is the link : https://leetcode.com/list/98u3f9f6 and also some questions which are not in the link like leetcode premium and geeksforgeeks questions are in the excel sheet this is the link of excel sheet:https://docs.google.com/spreadsheets/d/1GOqzyKaoi7TgkAAfiQMwpBRynHtKWvgb/edit?usp=sharing&ouid=103167723761039315431&rtpof=true&sd=true
Hi,
I also tried to solve it after seeing your post using BFS and added it as a post since I could not find concise BFS solutions.
https://leetcode.com/problems/spiral-matrix/discuss/1719416/C%2B%2B-Clean-and-Concise-BFS
Both solutions are fine. The downside to this one is that it is not extensible for added requirements (unique sets with duplicate numbers, etc) that you would find on similar questions.
See approach three here: https://leetcode.com/problems/subsets-ii/solution/
https://leetcode.com/problems/valid-palindrome/
here is the link to the problem. It says to remove all non-alphanumerics which I am doing with isLetterOrDigit()
You can find the greedy approach for solving the problem : LC 1326 Solution
if it does make you feel better, I bomb this question https://www.hackerrank.com/challenges/java-loops-i/problem?isFullScreen=true for 100k SDET position lmao! but I'm now learning easy/medium leet questions
cool. I have added the schedule and set of problems please feel free to copy the spreadsheet and start :)
LeetCode has an explore feature https://leetcode.com/explore/learn/card/linked-list/ that discusses linked lists. I cross reference this against geeksForgeeks and wikipedia.
Well, Dynamic Programming problems are particularly tricky. The approach applies to a whole bunch of problem types.
Here's a bunch of DP problems categorized by pattern.
https://leetcode.com/discuss/study-guide/1308617/Dynamic-Programming-Patterns
Hi, thanks for the letting me know about that, I am absolutely fine with people pointing out any grammatical mistakes. While I did proof read it, there are bound to be a few slipped by. The first seems to be that I forgot to delete the revision when I changed the sentence and the second is actually the exact wording from leetcode's explore card so the source of that grammatical error stems from them (https://leetcode.com/explore/learn/card/queue-stack/232/practical-application-stack/). I don't believe there are many grammatical errors in the document, none of those who bought it have brought any up that and I did spent a great amount of time reading over all problems to clean it up.
That being said, I am absolutely fine with anyone suggesting revisions and changes that they would like to see but I can't just give out the study guide because it took a lot of work to make. Moreover, all updates to the study guide are absolutely free. Instead of paying for newer versions with updated text, you get it for free.
I have already taken your suggestions and updated the text so I do thank you. I will update the downloads after New Years. There is a discord, which you get access to after purchase, where you can make any suggestions on the study guide or things you would like to request.
The problems are from the explore cards found here: https://leetcode.com/explore/
The cards included are:
There are 139 problems:
With respect to the list, all the problems can be found in those cards. I will add any problems from new explore cards that I solve in when I solve them with no additional cost. I did not solve the premium problems because that's paid content.
Building a matrix is going to take O(M*N) time where the optimal solution for this question is O(N(Log(K)). It may be a constant lookup time but that's only going to be beneficial for questions with upper-bound time complexities of at least O(N*M) like a DFS/BFS on a matrix, something like this: https://leetcode.com/problems/pacific-atlantic-water-flow/. There aren't going to be many scenarios where a visited matrix will have more utility than a HashMap or HashSet I don't believe.
I’m not a huge Python expert as I usually code in JS. Pass-by-reference and pass-by-value are things that I struggled with when learning DP and other more advanced recursive function programming. I started doing “Drills” where I would figure out how to write the same code using either-or. It Really helped my programming because I got familiar with the advantages and disadvantages of each.
Here’s one of said drills with some explanation. Same code written five separate times - One version all arguments are pass-by-value, one has all pass-by-reference, there are two hybrid versions where I do half reference / assign, and one version with a helper function within the original function - this helper can modify the variable within the original function because it’s within it’s scope.
Here’s a link to how these concepts work in Python. It was interesting reading for me too. Looking to get more into Python soon. I started with it and was real comfortable with it for a while. Got into WebDev and went all-in on JS for a while tho.
Just received an email promo from leetcode for $30 off.
code: "THANKS2021".
If you have an Indian payment method, there is covid-19 relief campaign running, you may check at https://leetcode.com/subscribe/ directly.
I got Leetcode's annual subscription for $127
Nice job finding a solution. It's not often you see people take advantage of the built in api for Arrays.binarySearch.
But take a glance at the jump game problem. Non-optimized backtracking will result in TLE because 1 <= nums.length <= 104. The acceptance criteria of the interview problem calls says that 1 <= nums.length <= 10E9.https://leetcode.com/problems/jump-game/
I get a "Your file could not be accessed" error when I try to use it. I tried rebooting chrome & changing the access from only while on leetcode.com to 'when I click the extension'.
This is one resource I found - https://www.hackerrank.com/interview/interview-preparation-kit
It contains questions for every major topic
https://aws.amazon.com/ec2/instance-types/
Take notice of the typical bandwidth for ec2 offerings. Usually it’s between 10 Gbps to 25 Gbps (so about 1-3 GB/s). They have some 100 Gbps offerings as well
!problems Amazon
Absolutely bang out the high freq questions. Keep Amazon leadership principles doc sent by your recruiter open on your screen because they will ask
This is a classic LCS problem. You just run LCS on these two strings and find the difference and return said difference. Another similar problem: https://leetcode.com/problems/delete-operation-for-two-strings/. The dp part is LCS, you are expected to implement it from scratch. There is no need to come up with a “custom” dp algorithm just for this problem IMO, but it could differ from interviewer to interviewer.
I know the run time can vary for each submission. I spam submissions a lot to check the variance. These two submissions are just consistently 100 ms apart.
There's also this problem Walls and Gates where which a regular BFS (or DFS) times out one test case. I looked at YouTube tutorials and leetcode discussion solutions and saw them write the exact same code that no longer works. I even copy and pasted from the discussion to check.
How are they defining a subset? Because I believe my comment makes a good point.
i think good approach is use leetcode to memorize new knowledge after DS lessons, i started in this way 2 weeks ago, so far so good. For example, after lessons about stack i tried to solve 1-3 problems with stack, ex. MinStack
Hey, any chance you can send me a few screenshots for the top voted solutions in the discussion tab for https://leetcode.com/problems/basic-calculator-iii/?
This is my plan, not sure if it's going to work, but here it is:
A super easy way to do this - Also really helpful for a ton of other problems - is to traverse the tree and add Depth and Parent attributes to the nodes. (Can also easily be stored in hash maps if an interviewer doesn’t want you to modify the tree nodes themselves.) This isn’t necessarily the most optimal way to do things depending on the question, but if you ever get a problem like this and you don’t know a great solution, it can help a ton.
Can do something like this easily enough - LeetCode LCA Add Parent and Depth Solution
It annoys me when I see this 300 number thrown around. It discourages people and for most it is insanely overkill.
OP, try this list of 75 questions to start: https://leetcode.com/discuss/general-discussion/460599/blind-75-leetcode-questions
If you can understand and solve most of these problems, then you’re pretty much ready. 300 is some bullshit arbitrary number. That’s like someone asking “how much weight do I need to lose to be skinny” and people saying “200 pounds” in response, no matter how overweight you are. 300 is a very high number and realistically you’ll probably be fine with just the 75 in the link above if you already have a background in CS. Either way, it’s a more manageable goal to complete 75 questions than it is 300.
Try not to use static class variables in leetcode. It leads to issues like this.
If you change the ArrayList to simply be public or private it'll work. I just did it and it worked fine : https://leetcode.com/submissions/detail/468279896/
I also had those doubts and this post really helped. And leetcode explore is also really good. I wish they had one on graphs too.
I did this problem yesterday too !
First, don't worry about this fancy solution, it was not the goal of the question, and I don't think they are expecting you to figure out it's a geometric series, unless you are applying for a closely related math position like Data Scientist.
This is my solution
class Solution: def numWaterBottles(self, numBottles: int, numExchange: int) -> int: ans = 0 remaining_empty = 0
while numBottles > 0: ans+= numBottles numBottles, remaining_empty = (remaining_empty+numBottles) // numExchange, (remaining_empty+numBottles) % numExchange
return ans
As of your initial question, this is the comment in a discussion thread that has your answer.
I think the gotcha part is that it asks you to do it without sorting, so there's a bit more variance in the way you can check the array.
Here's my solution in case you're interested : https://leetcode.com/submissions/detail/437835306/
I think the easiest way to do it in O(N) time is to use a map or set to see what numbers were seen, and then try to catch some missing number in the set or if that's not the case simply iterate until you get a number outside of the maximum.
I was asked the wildcard matching: https://leetcode.com/problems/wildcard-matching/description/
Now after designing a brute force solution, interviewer dismisses my attempts to come up with an optimal solution and proceeds to ask me the
100 coins 5 pirates puzzle. Ughhh, Microsoft, why?
This is after solving Leetcode mediums in previous rounds that day. Interviewer was very rude and dismissive. Oh well.
Right, that's what I thought. I'm just trying not make a habit of using built-in functions. Like for example, most Python3 answers I saw for https://leetcode.com/problems/reverse-words-in-a-string-iii/ were something like this:
def reverseWords(self, s): return ' '.join(s.split()[::-1])[::-1]
where mine was:
class Solution: def init(self): self.result = []
def split(self, string: str) -> list: split_result = [] temp = '' for char in string: if char == ' ': split_result.append(temp) temp = '' else: temp += char if temp != '': split_result.append(temp) return split_result
def reverse(self, s: str) -> str: for i in range(len(s) -1, -1, -1): self.result.append(s[i])
def reverseWords(self, s: str) -> str: s = self.split(s) for i in range(0, len(s)): if i > 0: self.result.append(" ") self.reverse(s[i]) return "".join(self.result)
I guess my only worry would be if an interviewer would see my approach as over engineered.
I just solved this one, probably the reason your having trouble with it is that you aren't seeing that each row and column represents a person (e.g. row 0 represents person 0, col 0 also represents person 0.) Also the code that individual posted is almost intentionally obfuscated.
So a 1 at [2][3] means that person 2 is friends with person 3.
Hopefully my post with comments is more intelligible.
https://leetcode.com/problems/friend-circles/discuss/790446/Java-dfs-with-explanation
this person had a similar issue with js
Hey cool problem, I couldnt discover the solution by myself, but I guess this guy explained it clearly: https://leetcode.com/problems/perfect-rectangle/discuss/87180/O(n)-solution-by-counting-corners-with-detailed-explaination
Can you be more specific where u got troubles understanding?
It allows applying the same recurrence relation to the lower boundaries (i=0, j=0) of the dp array / matrix.
Eg. on a 2-D problem, you can get access to DP[i-1][j-1] on the edges, even when i=0 and/or j=0. Avoid having to write special code for the initial conditions. This only works if the initial conditions can be rewritten as the recurrence relation using prior values of 0 (or any value you can instantiate your whole dp array too, like perhaps 1 if the relation is multiplicative). We just add an extra row/column which instantiate to this initial value, and voila! Saved writing an extra special loop for first row/column or using if statements to handle boundaries.
The illustration in this Leetcode post on the LCS (Least Common Sequence) does a great job of explaining the concept.
>Anyone familiar with the problem X of a Kind in a Deck of Cards
is it this one? -> https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/
Send the problem web-link and we'll be happy to advise.
IANAL, but you'd probably be in violation of the following clause in their ToS:
>You further agree that you do not allow any third party to use your account or use your account for any services not associated with your personal property or property for which you have lawful control.
But I think they're pretty much as lax as possible when it comes to enforcement.
For me, a good check would be, whenever you notice that your problem might have a singly linked list loop, think of Floyd's Fast and Slow.
e.g. https://leetcode.com/problems/find-the-duplicate-number
Clear case of a cycle, that would help get me an O(n)/O(1) solution
The DS itself is a super simplistic one, but it is easy to go down a rabbit hole with any problem. I have spent a lot of time today on this, easy looking problem: https://leetcode.com/problems/copy-list-with-random-pointer/
Today this happened on contains duplicate ii problem:
let sWindow = new Set() // ... for (let i=k+1; i<nums.length ;i++) { sWindow.delete(sWindow.values().next().value); // ...
=> 260 ms
let sWindow = new Set() // ... for (let i=k+1; i<nums.length ;i++) { sWindow.delete(nums[i-k-1]) // ...
=> 60 ms
Wouldn't you expect sWindow.values().next().value
to be O(1)? JS pls.
I have not played with notes myself. Is this https://leetcode.com/notes/ what you are referring to?
How does note-taking actually work, is it possible to take notes problem wise? Maybe I can work on that and update the project if I understand how the note system works.
cant find the LC link but here is an example in Haskell https://github.com/cmk/HR-Haskell/blob/master/globalMaximum.hs
For learning DS and Algo leetcode is not sufficient as it provides direct interview questions, which most of the time require tricky and weird logic. I like topcoder Algorithm toturial (https://www.topcoder.com/community/competitive-programming/tutorials/) for learning new topics and for practice both topcoder and codeforces has good problems
Hi, do you time out on the example case as well? Also, which problem?
I am not super well-versed in Python but I found these two solutions which appear to be the exact same as mine, but in Python.
https://leetcode.com/problems/number-of-islands/discuss/56340/Python-Simple-DFS-Solution
Looks like an extension of the sliding window maximum problem: https://leetcode.com/problems/sliding-window-maximum/discuss/407005/easy-to-understand-sliding-window-use-double-ended-queue Use a deque to track the maximums in the window
https://leetcode.com/problems/shortest-path-visiting-all-nodes/description/
I feel like I'm missing a key component here. I know BFS give's you the shortest path, so you BFS from each node and return the first path that visits everything -- but what's with all the bit manipulation stuff?
That works, but I'd like to see it reflected in the difficulty counts section too.
Assuming 2 locked questions were solved:
6/702 Solved -- hide locked --> 4/559 Solved
As for the JS, maybe this will help: https://leetcode.com/api/problems/algorithms/
Tree representation is covered in the faq https://leetcode.com/faq/
Your method takes in and returns TreeNode objects which are defined at the top. You don't need any code that directly deals with arrays. They are just an easy way to visualize / initialize binary trees.
What you have above would work. Or you could write a new TreeNode constructor that takes in an Integer[] and automatically builds the tree:
TreeNode root = new TreeNode(new Integer[]{7,11,30,22,48,null,null,23,56});