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
@shalsteven3 жыл бұрын
10:53 why we need to remove the last element? Just to clear the storage?
@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Ай бұрын
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()
@jaybibodi4 жыл бұрын
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() ??
@techdose4u4 жыл бұрын
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.
@shobhitmittal772 жыл бұрын
Solution starts at 8.30
@sudhanshukumar15584 жыл бұрын
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 👍
@techdose4u4 жыл бұрын
You can read about implementation of conversion to list. It's avg time must be greater than O(1).
@ShreyaSingh-vr9qi4 жыл бұрын
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; }
@techdose4u4 жыл бұрын
👍
@ashutoshtiwari47193 жыл бұрын
Thank You !! The question was simple only the way it was portrayed was confusing 😅😅
@agileprogramming74634 жыл бұрын
Awesome as always!
@techdose4u4 жыл бұрын
Thanx :)
@kunalsoni76814 жыл бұрын
Helpful video too much 😇😊. Thank you so much sir
@techdose4u4 жыл бұрын
Welcome
@АлишерХасен-к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
@techdose4u4 жыл бұрын
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 :)
@mehulvarshney33893 жыл бұрын
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
@akshataggarwal32777 ай бұрын
Stack
@eshaanpandey73532 жыл бұрын
Nice Explanation
@HimanshuSingh-ob9qo4 жыл бұрын
Nice explanation
@techdose4u4 жыл бұрын
Thanks :)
@PankajGupta-gh9cm4 жыл бұрын
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
@awwsumkush85814 жыл бұрын
In java arraylist is implemented as array so under the hood the left shift will happen
@techdose4u4 жыл бұрын
If this is true then you can't just use array list. Simply use a combination of array and map as I shown.
@Yash-uk8ib3 жыл бұрын
why do we need update the index incase of deletion, we are not interested for its index right?
@amitavamozumder733 жыл бұрын
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)
@ASocial0934 жыл бұрын
You were from Metallurgy. So, which books did you read for Programming C++ that you knew it so well.
@techdose4u4 жыл бұрын
No book.
@MohitBhagwani944 жыл бұрын
@@techdose4u Then how your concepts are so solid? what did you do?
@techdose4u4 жыл бұрын
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.
@topcoder38124 жыл бұрын
@@techdose4u Sir ,App kaha se preparation kiye the coding interview ke liye . Aap ka concept is very well. Please Sir..
@shyamprakashm63254 жыл бұрын
To check into the map whether the key is present or not .it does take o(n) time doesn't it?
@techdose4u4 жыл бұрын
No. Maximum logN time.
@shyamprakashm63254 жыл бұрын
@@techdose4u 🙄🙄 how does it take log n time.could you explain it me? Please
@techdose4u4 жыл бұрын
Elements are stored in balanced binary search tree. In a BST, you can search KEY in just O(logN) when it is balanced.
@shyamprakashm63254 жыл бұрын
Thanks
@techdose4u4 жыл бұрын
Welcome :)
@yjj4104 жыл бұрын
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_athlete4 жыл бұрын
this is a great approach. the same one came to my mind too
@sagargupta16153 жыл бұрын
Using array and hashmap we can als search item in o( 1) only
@RCVISHNUVardhan4 жыл бұрын
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!!!
@techdose4u4 жыл бұрын
It won't be correct because get Random is O(N) here. You need O(1) avg for all operations.
@RCVISHNUVardhan4 жыл бұрын
@@techdose4u Ok , Thank you.
@rohithkumartangudu46644 жыл бұрын
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.
@techdose4u4 жыл бұрын
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 😅
@rohithkumartangudu46644 жыл бұрын
@@techdose4u Yes I also agree. But I did not observed the time clearly.Thats why I implemented like that.
@hritiksharma71544 жыл бұрын
Sir from where should I c++ could you recommend me any course
@techdose4u4 жыл бұрын
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 😅
@thadpadvines52124 жыл бұрын
Which software u used in video editing, can u please tell..
@jnaneswarreddy81254 жыл бұрын
good explanation..... can i know how to implement if dupilcates are allowed
@manthankhorwal14774 жыл бұрын
That will be a different question ... Here we need probability to get every number should be same
@techdose4u4 жыл бұрын
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-rg1mv4 жыл бұрын
Thanks a lot sir!
@techdose4u4 жыл бұрын
Welcome :)
@lovleshbhatt77974 жыл бұрын
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
@techdose4u4 жыл бұрын
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.
@PUNEETRAIPURIA4 жыл бұрын
sir can you explain Red-Black tree in future video? thank you in advance
@techdose4u4 жыл бұрын
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.
@ashutoshbhadauriya74234 жыл бұрын
Can't we use unordered set?
@AyushGupta-mm4jg3 жыл бұрын
getRandom would be O(n)
@kushagrajain24074 жыл бұрын
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()) } }
@MrArpit12344 жыл бұрын
you have not added bounds to random function return rand()%size()
@HimanshuSingh-ob9qo4 жыл бұрын
👍
@techdose4u4 жыл бұрын
👍
@HimanshuSharma-tm2ms4 жыл бұрын
please add "find median of two sorted arrays of different sizes" to your list:)
@kavyap71134 жыл бұрын
too many ads , hard to follow
@sonuagarwal76794 жыл бұрын
Code will crash when we will have only one element and we need to remove that..