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
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು 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).