Skip to content

Randomized Algorithms

Table of Contents

398. Random Pick Index

  • LeetCode | 力扣

  • Tags: Hash Table, Math, Reservoir Sampling, Randomized

382. Linked List Random Node

  • LeetCode | 力扣

  • Tags: Linked List, Math, Reservoir Sampling, Randomized

384. Shuffle an Array

470. Implement Rand10() Using Rand7()

  • LeetCode | 力扣

  • Tags: Math, Rejection Sampling, Randomized, Probability And Statistics

528. Random Pick with Weight

  • LeetCode | 力扣

  • Tags: Array, Math, Binary Search, Prefix Sum, Randomized

710. Random Pick with Blacklist

  • LeetCode | 力扣

  • Tags: Array, Hash Table, Math, Binary Search, Sorting, Randomized

478. Generate Random Point in a Circle

  • LeetCode | 力扣

  • Tags: Math, Geometry, Rejection Sampling, Randomized

497. Random Point in Non-overlapping Rectangles

  • LeetCode | 力扣

  • Tags: Array, Math, Binary Search, Reservoir Sampling, Prefix Sum, Ordered Set, Randomized

519. Random Flip Matrix

  • LeetCode | 力扣

  • Tags: Hash Table, Math, Reservoir Sampling, Randomized

380. Insert Delete GetRandom O(1)

import random


class RandomizedSet:
    def __init__(self):
        self.nums = []
        self.pos = {}  # num: idx

    def insert(self, val: int) -> bool:
        if val in self.pos:
            return False
        self.pos[val] = len(self.nums)
        self.nums.append(val)
        return True

    def remove(self, val: int) -> bool:
        if val not in self.pos:
            return False

        idx = self.pos[val]
        last_val = self.nums[-1]
        self.nums[idx] = last_val
        self.pos[last_val] = idx

        self.nums.pop()
        del self.pos[val]
        return True

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


def test_RandomizedSet():
    obj = RandomizedSet()
    assert obj.insert(1)
    assert not obj.remove(2)
    assert obj.insert(2)
    assert obj.getRandom() in [1, 2]
    assert obj.remove(1)
    assert not obj.insert(2)
    assert obj.getRandom() == 2

381. Insert Delete GetRandom O(1) - Duplicates allowed

1515. Best Position for a Service Centre

1968. Array With Elements Not Equal to Average of Neighbors