Time Based Key-Value Store - Leetcode 981 - Python

  Рет қаралды 111,836

NeetCode

NeetCode

Күн бұрын

Пікірлер: 89
@rowanus116
@rowanus116 11 күн бұрын
For anyone who may experience the TLE in C++, swift, when you do vector vals = map[key], basically you're copying everything from map to vals, which is O(n). This is language-specific, some languages would return the vector result as a reference while others might return it as value(copy).
@demonsnails
@demonsnails 16 сағат бұрын
Thank you for this comment! I got it working when I used - vector& vals = map[key]
@halahmilksheikh
@halahmilksheikh 2 жыл бұрын
That's so interesting. I didn't know you could find the closest elements this way if the value being searched for doesn't exist in a binary search. Never would have thought of that.
@Eren-bb8qx
@Eren-bb8qx Жыл бұрын
Instead of setting res in every step; if the element not found in the search loop, you can also return the element that "r" points to. Explanation: In the last step of the loop, all l,m,r pointers will be showing the same position. If the target is bigger than m, then r is the biggest element that is less than target. If target is less than m, then r will be pointed m-1 and r is the biggest element that is less than target. resulting code: def get(self, key: str, timestamp: int) -> str: values = self.keyStore.get(key, []) l, r = 0, len(values) - 1 while l timestamp: r = m - 1 else: return values[m][0] if r!=-1: return values[r][0] return ""
@ashkan.arabim
@ashkan.arabim 5 ай бұрын
I watched the video for this one specifically because I wanted to see a nicer way of finding a close value! Gotta love this guy.
@dianav357
@dianav357 3 жыл бұрын
i hated this problem but ur explanation made it less complicated ty
@diojoestar5178
@diojoestar5178 7 күн бұрын
As soon as he read the fine print at the end of the problem it was just so clear and I didn't have to watch the rest to solve it. Thanks for being a good explanator hahah
@bag_of_pixels
@bag_of_pixels 2 ай бұрын
13:49 i've forgot `left
@nishiketsingh5283
@nishiketsingh5283 5 ай бұрын
I got this problem on an interview, if only I was subscribed to you back then.
@nguyentuan1990
@nguyentuan1990 4 ай бұрын
for real? can you share which company?
@nishiketsingh5283
@nishiketsingh5283 4 ай бұрын
@@nguyentuan1990 it was for soti
@chrischika7026
@chrischika7026 2 ай бұрын
which company plz
@nishiketsingh5283
@nishiketsingh5283 2 ай бұрын
It was Soti
@adeniyiadeboye3300
@adeniyiadeboye3300 2 жыл бұрын
you are a leetcode legend!...i have watched a couple of your leetcode videos solution
@NeetCode
@NeetCode 2 жыл бұрын
Thanks :)
@gregorvm7443
@gregorvm7443 Жыл бұрын
I was racking my brain with this, didn't read or realize that timestamp was in increasing order, I even implement a sort method in the set so that the array was sorted and the get could be done in log n time, but it wasn't enough some test failed because the time keep running out, then I saw that part of the video expecting some fancy algorithm and was like ._. oh? it's already sorted.
@boojo3
@boojo3 Жыл бұрын
yea me2 lol i tried sorting it
@eshanpandey4186
@eshanpandey4186 9 ай бұрын
same, i also failed after 44/53 test cases because of sorting
@yugioh8810
@yugioh8810 5 ай бұрын
in this case I think you can use a priority queue implemented with a binary search tree. you would be able to have get in O(logn) and insert in O(logn)
@arkamukherjee457
@arkamukherjee457 2 жыл бұрын
"Questions to ask in real interviews" - I'd love if you share thoughts on this topic on other problems too! In my experience, it makes a big difference, especially if you can't solve a problem during the interview.
@netratuse503
@netratuse503 Жыл бұрын
Yes much needed. Questions to ask during interview
@Dhruvbala
@Dhruvbala 7 ай бұрын
Nice. And for binary search, could just use right pointer at end of loop -- as that should be the closest value less than target
@symbol767
@symbol767 2 жыл бұрын
Damn I love this problem and your explaination, thank you man! Liked again and commenting to support!
@baolingchen2891
@baolingchen2891 2 жыл бұрын
Very concise solution and easy to understand. Thank you!
@ece116pranaykumar4
@ece116pranaykumar4 2 жыл бұрын
mapmp; void set(string key, string value, int timestamp) { mp[key].push_back({value,timestamp}); } string get(string key, int timestamp) { auto it=mp[key]; int high=it.size()-1; int low=0; string ans=""; while(low
@rishabhthakur2270
@rishabhthakur2270 2 жыл бұрын
there seems to be a problem in your get function, you missed to check if the given key actually exists in the map or not here, have a look at my code which is almost similar to yours but with the check void set(string key, string value, int timestamp) { mp[key].push_back(make_pair(value,timestamp)); } string get(string key, int timestamp) { // run binary search on the value list if(mp.find(key)==mp.end())return ""; string res=""; int l=0,h=mp[key].size()-1; while(l
@dusvn1484
@dusvn1484 3 ай бұрын
This video help me how to find optimal solution. What is my first solution: Implement binary search and if value is not finded just go from the end of array,becouse last element is with highest timestamp and check if we can find value < then timestamp. So now you can see this is time compl of O(n) + O(log n) but O(n) is dominant then time complexity in worst case will be O(n),but in general they will be better but we are looking for worst case.
@jsanity
@jsanity Ай бұрын
one small mem optimization i ended up making was just replacing the timestamp at the end of backing store if added item was same. so [ add(a,b,1), add(a,b,2) , add(a,b,3) ] in sequence ended with { a : (b,3) } if self.store[key][1] == value: self.store[key][0] = timestamp
@enterprisecloudnative8757
@enterprisecloudnative8757 2 жыл бұрын
i don't understand why the nested part can't be another hashmap like a nested dictionary. in the nested dictionary, timestamp is a string
@frankl1
@frankl1 2 жыл бұрын
It's because a dictionary is unordered, and you need an ordered data structure in order to apply binary search
@enterprisecloudnative8757
@enterprisecloudnative8757 2 жыл бұрын
@@frankl1 some languages dict is ordered ie python3
@frankl1
@frankl1 2 жыл бұрын
@@enterprisecloudnative8757 I didn't know that, do you have any reference to share ?
@toolworks
@toolworks 2 жыл бұрын
@@frankl1 Dict is ordered, but you aren't supposed to rely on that. It used to be unordered, and OrderedDict exists for ordered dictionaries. It was a later patch which changes how dicts are implemented in Python and now they are ordered by default sort of by accident. I recommend the talk "Modern Dictionaries" by Raymond Hettinger.
@iamnoob7593
@iamnoob7593 4 ай бұрын
Thanks neetcode , Presentation is really good
@sidazhong2019
@sidazhong2019 Жыл бұрын
I don't wanna abuse Python too much to make everything so easy. lol
@zishiwu7757
@zishiwu7757 2 ай бұрын
I recently took a CodeSignal online assessment that contained this problem but with additional method compare_and_set which checks if the current value stored at key equals expected_value, and if that condition is true only then do we update the key to store new_value. Man I wish I had seen this video a week before. Oh well, you live and you learn.
@PradyumnVij
@PradyumnVij Ай бұрын
wouldn' t it be easier to use a TreeMap as the Values method? So something like Map. You have access to "lowerKey" method as well.
@mayankpant5376
@mayankpant5376 11 күн бұрын
thats what i was thinking but insertion is nLogn
@servantofthelord8147
@servantofthelord8147 Күн бұрын
Bisect Right. Nice.
@sheikhmkrifat7749
@sheikhmkrifat7749 7 ай бұрын
This problem statement is really badly written
@Jason-be2cy
@Jason-be2cy 3 жыл бұрын
I really love your videos! Could you upload a video for "843. Guess the Word"? (Top google question)
@NeilSharma-u5n
@NeilSharma-u5n 5 ай бұрын
yeah i was able to solve this myself once i saw that constraint.
@shreyaschaudhary-r6d
@shreyaschaudhary-r6d 3 ай бұрын
love this question!
@zenulee
@zenulee 7 ай бұрын
So we assume the input timestamp(s) are always ascending for each key/value? For example they cannot give you ["foo", "bar", 4] then ["foo", "bar", 1]?
@saideep7510
@saideep7510 2 ай бұрын
No its always ascending, as mentioned in the question.
@krateskim4169
@krateskim4169 2 жыл бұрын
Awesome explanation
@Emorinken
@Emorinken 2 ай бұрын
Thank you very much man
@jonnatanortiz7159
@jonnatanortiz7159 Жыл бұрын
Great explanation, thank you!
@ameynaik2743
@ameynaik2743 3 жыл бұрын
Nice solution. Can you please do a video on 68. Text Justification from leetcode?
@NeetCode
@NeetCode 3 жыл бұрын
Sure, will try to do it this week
@jmarti1997jm
@jmarti1997jm 2 жыл бұрын
@@NeetCode have you given text justification a try haha
@metarus208
@metarus208 2 жыл бұрын
what is the justification for this request? :P
@Whatthetrash
@Whatthetrash 13 күн бұрын
Thank you!! :)
@TheQuancy
@TheQuancy 2 жыл бұрын
Can anyone explain why we write the binary search that way? I usually have 3 conditions in my binary search
@sf-spark129
@sf-spark129 Жыл бұрын
Well, think of this way. The goal of this problem is to find the value that matches the given timestamp. If that given timstamp doesn't exit in the hashMap's key, then the closest one. You can write it your way: if values[mid][1] < timestamp: res = values[mid][0] l = m + 1 elif values[mid][1] < timestamp: r = m -1 else: res = values[mid][0] break Or you can do it NeetCode's way: if values[mid][1]
@grhaonan
@grhaonan Жыл бұрын
I am getting time limit exceeded with this solution or it is just me? thanks
@PawanSingh-i5e5g
@PawanSingh-i5e5g Жыл бұрын
Same time limit exceeded
@erickpeculiar823
@erickpeculiar823 6 күн бұрын
bro I didn't even know it was a binary search
@boli7171
@boli7171 8 ай бұрын
The answer will be wrong if I gave while (l
@awesomedavid2012
@awesomedavid2012 8 ай бұрын
it will be wrong in the case where the exact value doesn't exist. You seem to never return the closest value below as the problem desires.
@LavanVivekanandasarma
@LavanVivekanandasarma Жыл бұрын
The goat fr
@anonlegion8331
@anonlegion8331 Ай бұрын
Any one know how did he condense that line at 11:11?
@dheerajchidambaranathan
@dheerajchidambaranathan 2 жыл бұрын
Why did you choose to save the zeroth element of the value dictionary and not the 1st which satisfied the condition of time stamp being less than or equal to queried time stamp?
@hwang1607
@hwang1607 Жыл бұрын
The 0th element is the value that you return but the 1st value is the timestamp
@gurazeez
@gurazeez 2 жыл бұрын
if I write values =self.store[key] instead of self.store.get(keys,[]), the run time difference is huge, why is get() so much faster ??
@mastermax7777
@mastermax7777 Жыл бұрын
leetcode run time is not precise. Did you run it multiple times and its really different? It doesnt make much sense
@GenevieveKochel
@GenevieveKochel 2 ай бұрын
I'm getting a TLE for this solution
@kuoyulu6714
@kuoyulu6714 Жыл бұрын
"I don't want to make it too easy"
@naimeimran3247
@naimeimran3247 2 жыл бұрын
Thanks
@Zynqify
@Zynqify Жыл бұрын
of course for lists that are much much bigger in size the binary search option is still better with a time complexity of O(log n), but i feel like there's a much simpler approach that is O(n) at worst. since the timestamps are always in increasing order, we can iterate through the timestamps backwards and return the value whose timestamp is less than or equal to the input timestamp, otherwise return an empty string. class TimeMap: def __init__(self): self.pairs = {} def set(self, key: str, value: str, timestamp: int) -> None: if key in self.pairs: self.pairs[key].append((value, timestamp)) else: self.pairs[key] = [(value, timestamp)] def get(self, key: str, timestamp: int) -> str: if key not in self.pairs: return "" else: for values in reversed(self.pairs[key]): if values[1]
@indhumathi5846
@indhumathi5846 Жыл бұрын
understood
@AndreiSokolov-k7j
@AndreiSokolov-k7j 8 ай бұрын
I think that problem should be easy
@trungthanhbp
@trungthanhbp 3 жыл бұрын
nice bro
@goodguy6589
@goodguy6589 2 жыл бұрын
What about java code...?
@nnamdiadom8256
@nnamdiadom8256 2 жыл бұрын
Time Limit Exceeded with same solution
@Princebharti9971
@Princebharti9971 Жыл бұрын
I am getting TLE for same solution in Swift, anyone can help ? I have written down the solution below. class TimeMap { private var dictionary = [String: [(Int,String)]]() init(){} func set(_ key: String, _ value: String, _ timestamp: Int) { var list = dictionary[key] ?? [] list.append((timestamp, value)) dictionary[key] = list } func get(_ key: String, _ timestamp: Int) -> String { var result = "" let array = dictionary[key, default: []] var left = 0, right = array.count-1 while left
@TarunKumar-qs9dj
@TarunKumar-qs9dj Жыл бұрын
Your language could be the hurdle, change your language to some mainstreams language
@mastermax7777
@mastermax7777 Жыл бұрын
this is the answer that chatgpt gave me, and its shorter and 95% faster than every other answer... import bisect from collections import defaultdict class TimeMap: def __init__(self): self.data = defaultdict(list) def set(self, key, value, timestamp): self.data[key].append((timestamp, value)) def get(self, key, timestamp): values = self.data[key] index = bisect.bisect_right(values, (timestamp, chr(127))) if index: return values[index - 1][1] return "" edit: I understand why he didnt do it this way now, he said "he didnt want to abuse java" and wanted it to be more similar to other languages
@JoseAntonio-sn6sf
@JoseAntonio-sn6sf Жыл бұрын
I think there is no need to use binary search because according to the condition, the timestamps are strictly set in increasing order, so the right most index has the max timestamp which you can compare it with the current timestamp, so you could condense the get function like: def get(self, key, timestamp): res = " " values = self.store.get(key, []) if values[-1][1]
@jointcc2
@jointcc2 Жыл бұрын
the whole point of binary search is to continually search for the nearest smallest value, if the given timestamp is smaller does that mean the nearest smallest value cannot be found? I don't think so.
@JoseAntonio-sn6sf
@JoseAntonio-sn6sf Жыл бұрын
@@jointcc2 oh yeah i though that the gets operations where going to ask for time values in increasing order as the example but in reality it could ask for any time value
@masternobody1896
@masternobody1896 3 жыл бұрын
I dont get it
@dev_among_men
@dev_among_men 3 жыл бұрын
Hash map to store all the values for a key and binary search to find time stamp as list is sorted
@masternobody1896
@masternobody1896 3 жыл бұрын
@@dev_among_men still dont get it
@dev_among_men
@dev_among_men 3 жыл бұрын
Try to do this question, Find index of element in sorted array if not present get index of the number just smaller than it.
@hemantkarasala5767
@hemantkarasala5767 3 жыл бұрын
@@masternobody1896 would help if you mentioned which aspect you didn't get.
@masternobody1896
@masternobody1896 3 жыл бұрын
@@hemantkarasala5767 i guess i need to do some basic leetcode to understand
@gugolinyo
@gugolinyo 2 жыл бұрын
At first I thought of a TreeMap. Then I saw your video and thought otherwise. Then I realized I discarded my initial idea just because I thought that to be something like a brute force solution. Taking advantage of the fact that TreeMap implements NavigableMap I used floorEntry() to spare myself all that binary search clutter.
How I would learn Leetcode if I could start over
18:03
NeetCodeIO
Рет қаралды 695 М.
How I Failed the Google Coding Interview (and lessons I learned)
14:24
coco在求救? #小丑 #天使 #shorts
00:29
好人小丑
Рет қаралды 27 МЛН
Do you love Blackpink?🖤🩷
00:23
Karina
Рет қаралды 21 МЛН
Why no RONALDO?! 🤔⚽️
00:28
Celine Dept
Рет қаралды 84 МЛН
From Small To Giant 0%🍫 VS 100%🍫 #katebrush #shorts #gummy
00:19
Time Based Key Value Store | Netflix Coding Question | Binary Search
14:21
Valid Palindrome - Leetcode 125 - Python
14:58
NeetCode
Рет қаралды 279 М.
Sort Colors - Quicksort Partition - Leetcode 75 - Python
15:48
Minimum Time Difference - Leetcode 539 - Python
21:43
NeetCodeIO
Рет қаралды 8 М.
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Codebagel
Рет қаралды 303 М.
10 Math Concepts for Programmers
9:32
Fireship
Рет қаралды 1,9 МЛН
Task Scheduler - Leetcode 621 - Python
17:07
NeetCode
Рет қаралды 186 М.
coco在求救? #小丑 #天使 #shorts
00:29
好人小丑
Рет қаралды 27 МЛН