Design data structure | Insert Delete GetRandom O(1) | Leetcode

  Рет қаралды 27,089

Techdose

Techdose

Күн бұрын

Пікірлер: 77
@ishaankalia8049
@ishaankalia8049 2 жыл бұрын
this question can also be done using just only unordered_map the extra functionality to generate the random number would be using an srand(time(NULL)) function within your class contructor
@shalsteven
@shalsteven 3 жыл бұрын
10:53 why we need to remove the last element? Just to clear the storage?
@haidarmohammad8510
@haidarmohammad8510 Жыл бұрын
Sir, Why you are not inserting 3 twice in the array because in the problem structure it is given that we can insert dublicate numbers. Please explain...........
@aruneshsrivastava7154
@aruneshsrivastava7154 Ай бұрын
If you use an arraylist , in place of normal list , i think that can internally take care of shifting the elements when you call arraylist.remove()
@jaybibodi
@jaybibodi 4 жыл бұрын
In 2nd approach (Using set), why can't we return the first element everytime for getRandom()? Definition of getRandom in the problem is "Returns a random element from current set of elements. Each element must have the same probability of being returned." So ideally it is not necessary we use Random library to generate random number. What if we consider 1st element in the set as the random element and extract using set.iterator.next() ??
@techdose4u
@techdose4u 4 жыл бұрын
I don't think this will work because SET is maintained in a self balanced BST without caring about ordering (unordered_set) and so, you can get any orientation of set when you insert a new element which will minimize time. If have not gone through how the indexing is done in unordered_set but I think that will not be random. I have to check it otherwise you can create million random entries and pick the 1st element in a predefined unordered_set and see the distribution graph.
@shobhitmittal77
@shobhitmittal77 2 жыл бұрын
Solution starts at 8.30
@sudhanshukumar1558
@sudhanshukumar1558 4 жыл бұрын
In python I used a dictionary to insert and delete values, for get random I used randint() to get a random number and returned the list(keys of dict)[random number] Insert and delete are O(1), not sure if get random is O(1) or not. Thanks for sharing your solutions for this one 👍
@techdose4u
@techdose4u 4 жыл бұрын
You can read about implementation of conversion to list. It's avg time must be greater than O(1).
@ShreyaSingh-vr9qi
@ShreyaSingh-vr9qi 4 жыл бұрын
Nice solution !! I think there is no use of auto it : map.find(), we can simply do like this :- bool remove(int val) { if(!mp.count(val)) return false; mp[v.back()]=mp[val]; swap(v.back(),v[mp[val]]); v.pop_back(); mp.erase(val); return true; }
@techdose4u
@techdose4u 4 жыл бұрын
👍
@ashutoshtiwari4719
@ashutoshtiwari4719 3 жыл бұрын
Thank You !! The question was simple only the way it was portrayed was confusing 😅😅
@agileprogramming7463
@agileprogramming7463 4 жыл бұрын
Awesome as always!
@techdose4u
@techdose4u 4 жыл бұрын
Thanx :)
@kunalsoni7681
@kunalsoni7681 4 жыл бұрын
Helpful video too much 😇😊. Thank you so much sir
@techdose4u
@techdose4u 4 жыл бұрын
Welcome
@АлишерХасен-к7ю
@АлишерХасен-к7ю 4 жыл бұрын
The 1st method by using vector insertion will not be O(1) because you should know if you already have this number or not
@techdose4u
@techdose4u 4 жыл бұрын
It is O(1) on avg. Worst case is O(logN) because we are storing numbers encountered in map. Question says about avg and not worst case :)
@mehulvarshney3389
@mehulvarshney3389 3 жыл бұрын
Design an efficient Data Structure for the following operations. 1) findMin() : 2) findMax() : 3) deleteMin() : 4) deleteMax() : 5) Insert() : 6) Delete() : kindly help in this question, I heard map over some heap solution but couldn't find it
@akshataggarwal3277
@akshataggarwal3277 7 ай бұрын
Stack
@eshaanpandey7353
@eshaanpandey7353 2 жыл бұрын
Nice Explanation
@HimanshuSingh-ob9qo
@HimanshuSingh-ob9qo 4 жыл бұрын
Nice explanation
@techdose4u
@techdose4u 4 жыл бұрын
Thanks :)
@PankajGupta-gh9cm
@PankajGupta-gh9cm 4 жыл бұрын
can we use ArrayList instead of the array so that we don't need to copy the last element instead we directly remove from the map and also from ArrayList since after removing element its size decreases so there will be no problem for generating the random elements
@awwsumkush8581
@awwsumkush8581 4 жыл бұрын
In java arraylist is implemented as array so under the hood the left shift will happen
@techdose4u
@techdose4u 4 жыл бұрын
If this is true then you can't just use array list. Simply use a combination of array and map as I shown.
@Yash-uk8ib
@Yash-uk8ib 3 жыл бұрын
why do we need update the index incase of deletion, we are not interested for its index right?
@amitavamozumder73
@amitavamozumder73 3 жыл бұрын
why do we need an array or vector, the map it self can hold the value, we do insert, delete, find everything in the map itself, right? all are O(1)
@ASocial093
@ASocial093 4 жыл бұрын
You were from Metallurgy. So, which books did you read for Programming C++ that you knew it so well.
@techdose4u
@techdose4u 4 жыл бұрын
No book.
@MohitBhagwani94
@MohitBhagwani94 4 жыл бұрын
@@techdose4u Then how your concepts are so solid? what did you do?
@techdose4u
@techdose4u 4 жыл бұрын
I just search and study on internet as I had no time to go through books. Everything is already available on the Net. Keep searching as you wish.
@topcoder3812
@topcoder3812 4 жыл бұрын
@@techdose4u Sir ,App kaha se preparation kiye the coding interview ke liye . Aap ka concept is very well. Please Sir..
@shyamprakashm6325
@shyamprakashm6325 4 жыл бұрын
To check into the map whether the key is present or not .it does take o(n) time doesn't it?
@techdose4u
@techdose4u 4 жыл бұрын
No. Maximum logN time.
@shyamprakashm6325
@shyamprakashm6325 4 жыл бұрын
@@techdose4u 🙄🙄 how does it take log n time.could you explain it me? Please
@techdose4u
@techdose4u 4 жыл бұрын
Elements are stored in balanced binary search tree. In a BST, you can search KEY in just O(logN) when it is balanced.
@shyamprakashm6325
@shyamprakashm6325 4 жыл бұрын
Thanks
@techdose4u
@techdose4u 4 жыл бұрын
Welcome :)
@yjj410
@yjj410 4 жыл бұрын
my python implementation. I used dict and list both. Dict maps value of item to index of item in the list. To get random item, i just used random.choice() on list. class RandomizedSet: def __init__(self): """ Initialize your data structure here. """ self.data_key = {} self.data = [] def insert(self, val: int) -> bool: """ Inserts a value to the set. Returns true if the set did not already contain the specified element. """ if val in self.data_key: return False self.data.append(val) self.data_key[val] = len(self.data) - 1 return True def remove(self, val: int) -> bool: """ Removes a value from the set. Returns true if the set contained the specified element. """ if val not in self.data_key: return False ind = self.data_key[val] self.data_key[self.data[-1]] = self.data_key[val] del self.data_key[val] self.data[ind] = self.data[-1] self.data.pop() return True def getRandom(self) -> int: """ Get a random element from the set. """ return random.choice(self.data)
@yash_renaissance_athlete
@yash_renaissance_athlete 4 жыл бұрын
this is a great approach. the same one came to my mind too
@sagargupta1615
@sagargupta1615 3 жыл бұрын
Using array and hashmap we can als search item in o( 1) only
@RCVISHNUVardhan
@RCVISHNUVardhan 4 жыл бұрын
I have implemented the same thing with only dictionary( C# ) or insertion and deletion will be O(1) but for getting random number i am using like dictionary.keys.ToArray(). Converting dictionary keys to array Is this fine!!!! Or the code for getting random is not correct!!!
@techdose4u
@techdose4u 4 жыл бұрын
It won't be correct because get Random is O(N) here. You need O(1) avg for all operations.
@RCVISHNUVardhan
@RCVISHNUVardhan 4 жыл бұрын
@@techdose4u Ok , Thank you.
@rohithkumartangudu4664
@rohithkumartangudu4664 4 жыл бұрын
I got idea and solved using hashset in java and the solution is also accepted. Is there any problem with this solution??Even though I know getrandom function takes o(n) time.
@techdose4u
@techdose4u 4 жыл бұрын
Ummm....you should have tried to implement everything in O(1) avg. If you take one operation to be O(1) then the problem will not be challenging at all 😅
@rohithkumartangudu4664
@rohithkumartangudu4664 4 жыл бұрын
@@techdose4u Yes I also agree. But I did not observed the time clearly.Thats why I implemented like that.
@hritiksharma7154
@hritiksharma7154 4 жыл бұрын
Sir from where should I c++ could you recommend me any course
@techdose4u
@techdose4u 4 жыл бұрын
Ummm....You can pick any CPP book and read but I never read any book so can't really recommend 😅 You can do what I did. Just search the net whenever you are not able to understand something. This way you will learn. Books won't cover everything and I find it very boring too 😅
@thadpadvines5212
@thadpadvines5212 4 жыл бұрын
Which software u used in video editing, can u please tell..
@jnaneswarreddy8125
@jnaneswarreddy8125 4 жыл бұрын
good explanation..... can i know how to implement if dupilcates are allowed
@manthankhorwal1477
@manthankhorwal1477 4 жыл бұрын
That will be a different question ... Here we need probability to get every number should be same
@techdose4u
@techdose4u 4 жыл бұрын
You can take map of vector and maintain same element index in ASC order. You can apply binary search to search for index or linear search to access them all.
@AA-rg1mv
@AA-rg1mv 4 жыл бұрын
Thanks a lot sir!
@techdose4u
@techdose4u 4 жыл бұрын
Welcome :)
@lovleshbhatt7797
@lovleshbhatt7797 4 жыл бұрын
You didn't clear the map and vector then how you set AC, I got WA if I am not using clear commands for both vec and map
@techdose4u
@techdose4u 4 жыл бұрын
If you declared variables inside class then for different objects, the space allocated is totally different. So, it doesn't matter whether you clear it or not. I wrote thinking this and it got accepted. If you make variables global then you will have to clear it everytime an object is created.
@PUNEETRAIPURIA
@PUNEETRAIPURIA 4 жыл бұрын
sir can you explain Red-Black tree in future video? thank you in advance
@techdose4u
@techdose4u 4 жыл бұрын
Obviously YES. But it will take long time before I reach there. I am first planning on finishing the basic concepts. I want to maintain order. Teaching from here and there won't be useful in the long run.
@ashutoshbhadauriya7423
@ashutoshbhadauriya7423 4 жыл бұрын
Can't we use unordered set?
@AyushGupta-mm4jg
@AyushGupta-mm4jg 3 жыл бұрын
getRandom would be O(n)
@kushagrajain2407
@kushagrajain2407 4 жыл бұрын
Hey , I followed your approach and wrote my code in Kotlin and passed the Sample test case but getting an index out of Bound error on submission. I can't seem to figure out the Error in my code. Can anyone have a look at it and let me know. Thanks in advance :) Error: Line 26: Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3358, Size: 2141 Code: import kotlin.random.Random class RandomizedSet() { /** Initialize your data structure here. */ var map = hashMapOf() val elements: MutableList = mutableListOf() var count = 0 /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ fun insert(`val`: Int): Boolean { if(`val` in map.keys){ return false } else{ elements.add(`val`) map[`val`] = elements.size-1 return true } } /** Removes a value from the set. Returns true if the set contained the specified element. */ fun remove(`val`: Int): Boolean { if(`val` in map.keys){ if(elements.size >1){ var index = map[`val`] var key = elements[elements.size-1] elements[index!!] = key //Error in this line elements.removeAt(elements.size-1) map.remove(`val`) map[key] = index!! } else{ var index = map[`val`] elements.removeAt(index!!) map.remove(`val`) } return true } else{ return false } } /** Get a random element from the set. */ fun getRandom(): Int { return(elements.random()) } }
@MrArpit1234
@MrArpit1234 4 жыл бұрын
you have not added bounds to random function return rand()%size()
@HimanshuSingh-ob9qo
@HimanshuSingh-ob9qo 4 жыл бұрын
👍
@techdose4u
@techdose4u 4 жыл бұрын
👍
@HimanshuSharma-tm2ms
@HimanshuSharma-tm2ms 4 жыл бұрын
please add "find median of two sorted arrays of different sizes" to your list:)
@kavyap7113
@kavyap7113 4 жыл бұрын
too many ads , hard to follow
@sonuagarwal7679
@sonuagarwal7679 4 жыл бұрын
Code will crash when we will have only one element and we need to remove that..
@arpit5506
@arpit5506 2 жыл бұрын
noise
Insert Delete GetRandom O(1) - Leetcode 380 - Python
13:27
NeetCode
Рет қаралды 53 М.
Product of array except self | Leetcode #238
15:00
Techdose
Рет қаралды 98 М.
Quando A Diferença De Altura É Muito Grande 😲😂
00:12
Mari Maria
Рет қаралды 45 МЛН
She made herself an ear of corn from his marmalade candies🌽🌽🌽
00:38
Valja & Maxim Family
Рет қаралды 18 МЛН
Premature Optimization
12:39
CodeAesthetic
Рет қаралды 845 М.
Remove K digits | Build lowest number | Leetcode #402
15:30
Techdose
Рет қаралды 90 М.
LeetCode 432 - All O' one Data Structure - Java
22:36
Alpha-Code
Рет қаралды 675
LeetCode was HARD until I Learned these 15 Patterns
13:00
Ashish Pratap Singh
Рет қаралды 687 М.
Intro to Data Oriented Design for Games
52:35
Nic Barker
Рет қаралды 56 М.
Validate IP Address | Regex | Leetcode #468
26:32
Techdose
Рет қаралды 40 М.
How to Solve ANY LeetCode Problem (Step-by-Step)
12:37
Codebagel
Рет қаралды 330 М.
Quando A Diferença De Altura É Muito Grande 😲😂
00:12
Mari Maria
Рет қаралды 45 МЛН