Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 380 · Design

Insert Delete GetRandom O(1)

LeetCode 380 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

List + index map; delete by swapping with the last element.

मध्यमArrayHash TableMathDesignRandomized

मी Insert Delete GetRandom O(1) (LeetCode 380) असा सोडवला — Design पॅटर्नमधील एक मध्यम प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.

खालील विवरण इंग्रजीत आहे.

Intuition

A list gives O(1) random picks, a hash map gives O(1) membership. Keep both: the list stores values, the map stores each value's index. To delete in O(1), move the last element into the hole and pop the end.

Approach

  1. 1

    insert: reject duplicates, append, record the index.

  2. 2

    remove: look up the index, overwrite it with the last value, update that value's index, pop the end.

  3. 3

    getRandom: random.choice on the list.

मी कसा सोडवला

Array + hash mapPythonO(1) per op
class RandomizedSet:

    def __init__(self):
        self.data = []
        self.loc_map={}
    def insert(self, val: int) -> bool:
        if val in self.loc_map:
            return False
        self.data.append(val)
        self.loc_map[val]=len(self.data)-1
        return True
    def remove(self, val: int) -> bool:
        if val not in self.loc_map:
            return False
        remove_item_index = self.loc_map.get(val)
        last_item = self.data[-1]
        self.data[remove_item_index]=last_item
        self.loc_map[last_item]=remove_item_index
        del self.loc_map[val]
        self.data.pop()
        return True

    def getRandom(self) -> int:
        return random.choice(self.data)


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
स्टेप-थ्रू लोड होत आहे…

Insert Delete GetRandom O(1) — वारंवार विचारले जाणारे प्रश्न

Insert Delete GetRandom O(1) मागील intuition काय आहे?

A list gives O(1) random picks, a hash map gives O(1) membership. Keep both: the list stores values, the map stores each value's index. To delete in O(1), move the last element into the hole and pop the end.

Insert Delete GetRandom O(1) (LeetCode 380) कसा सोडवावा?

1. insert: reject duplicates, append, record the index. 2. remove: look up the index, overwrite it with the last value, update that value's index, pop the end. 3. getRandom: random.choice on the list.

Insert Delete GetRandom O(1) ची time आणि space complexity किती आहे?

Time: O(1) average per operation. Space: O(n). (Accepted approach: Array + hash map.)

Insert Delete GetRandom O(1) मध्ये सामान्य चुका कोणत्या?

Update the moved element's index before deleting the removed key (order matters when removing the last element).