Tutorialspoint
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.
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].
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
Hash MapFunctions / MethodsKPMGTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a dynamic array to store all elements including duplicates
 Step 2: Implement insert by adding the element to the end of the array
 Step 3: Implement delete by finding the element and swapping it with the last element
 Step 4: Decrease the size after deletion to maintain O(1) complexity
 Step 5: Implement getRandom by generating a random index within the current size
 Step 6: Return the element at the randomly generated index
 Step 7: Handle edge cases and ensure proper memory management

Submitted Code :