Leetcode 380: Insert Delete GetRandom O(1)

grid47
grid47
Exploring patterns and algorithms
Sep 30, 2024 7 min read

A sequence of elements being added or deleted, with each random selection softly highlighted.
Solution to LeetCode 380: Insert Delete GetRandom O(1) Problem

Design a data structure that supports three operations: insert, remove, and getRandom. The insert operation adds an element to the set if it is not already present. The remove operation removes an element from the set if it exists. The getRandom operation returns a random element from the set, with each element having an equal probability of being selected.
Problem
Approach
Steps
Complexity
Input: The input consists of multiple function calls, starting with the creation of the RandomizedSet object. The operations 'insert(val)', 'remove(val)', and 'getRandom()' are called sequentially.
Example: Example input: [[], [1], [2], [2], [], [1], [2], []]
Constraints:
• -2^31 <= val <= 2^31 - 1
• At most 2 * 10^5 calls will be made to insert, remove, and getRandom.
• There will always be at least one element in the set when getRandom() is called.
Output: The output is a list of results corresponding to the sequence of operations performed.
Example: Example output: [null, true, false, true, 2, true, false, 2]
Constraints:
Goal: Use a combination of a list and a hash map to efficiently perform insertions, removals, and random selections in constant time on average.
Steps:
• Use a list to store elements and a hash map to store their indices for fast access.
• In the insert operation, check if the element already exists. If not, add it to the list and map the value to its index.
• In the remove operation, replace the element to be removed with the last element in the list, update its index in the map, and then pop the last element.
• In the getRandom operation, simply pick a random index from the list.
Goal: Ensure the insert, remove, and getRandom functions work in O(1) time on average.
Steps:
• -2^31 <= val <= 2^31 - 1
• At most 2 * 10^5 calls to insert, remove, and getRandom.
Assumptions:
• The elements are stored uniquely in the set.
• The set will always have at least one element when getRandom() is called.
Input: Example 1: [[], [1], [2], [2], [], [1], [2], []]
Explanation: We track elements in the set, and after each operation, we provide the result for that operation. For example, 'insert(1)' returns true because 1 is inserted, while 'remove(2)' returns false because 2 was not in the set.

Input: Example 2: [[], [5], [], [10], [5], []]
Explanation: After each operation, the result is either true, false, or a random element from the set.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus