
Problem
Solution
Submissions
Insert Delete GetRandom O(1)
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to implement a data structure that supports insert, delete, and getRandom operations in O(1) average time complexity, allowing duplicate values. The data structure should efficiently handle multiple instances of the same value and return a random element with equal probability.
Example 1
- Input: insert(1), insert(1), insert(2), getRandom(), delete(1), getRandom()
- Output: true, true, true, 1 or 2, true, 1 or 2
- Explanation:
- Insert 1 twice and 2 once into the collection.
- getRandom() should return 1 or 2 with equal probability.
- Delete one instance of 1.
- getRandom() should still return 1 or 2 with equal probability.
- Insert 1 twice and 2 once into the collection.
Example 2
- Input: insert(4), insert(3), insert(4), insert(2), insert(4), delete(4), getRandom()
- Output: true, true, true, true, true, true, 2, 3, or 4
- Explanation:
- Insert multiple values including duplicates.
- Delete one instance of 4.
- getRandom() should return any remaining value with equal probability.
- The collection now contains [4, 3, 2, 4].
- Insert multiple values including duplicates.
Constraints
- 1 ≤ val ≤ 10^5
- At most 2 * 10^5 calls will be made to insert, delete, and getRandom
- There will be at least one element in the data structure when getRandom is called
- Time Complexity: O(1) average for all operations
- Space Complexity: O(n) where n is the number of elements
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use an array to store all elements (including duplicates) for O(1) random access
- Use a hash map to store indices of each value for O(1) lookup during deletion
- For deletion, swap the element to be deleted with the last element to maintain O(1) time
- Update the hash map entries when swapping elements
- Use rand() function to generate random indices for getRandom operation
- Keep track of the current size of the collection