Classic data structure design question in TikTok interviews. This article demonstrates how to achieve O(1) insertion, deletion, search, and random access. oavoservice helps you master advanced data structure design.
📋 Problem Reconstruction
Design a RandomizedSet supporting the following operations with average O(1) time complexity:
insert(val)- Insert element, return true if not present.remove(val)- Remove element, return true if present.search(val)- Check if element exists.getRandom()- Return a random element.
Constraint: Probability of each element being returned must be equal.
🎯 Core Challenges
- O(1) Insert/Delete - Fast location required
- O(1) Random Access - Index access needed
- Equal Probability - Ensure fairness
- Space Efficiency - Minimize overhead
💡 Solution Strategy (oavoservice Approach)
Method: Array + Hash Map
import random
class RandomizedSet:
def __init__(self):
self.data = [] # Store elements for random access
self.index_map = {} # {val: index} for O(1) lookup
def insert(self, val):
if val in self.index_map:
return False
self.index_map[val] = len(self.data)
self.data.append(val)
return True
def remove(self, val):
if val not in self.index_map:
return False
# Swap with last element to delete in O(1)
last_element = self.data[-1]
idx_to_remove = self.index_map[val]
self.data[idx_to_remove] = last_element
self.index_map[last_element] = idx_to_remove
self.data.pop()
del self.index_map[val]
return True
def getRandom(self):
return random.choice(self.data)
🚀 Deep Follow-ups
Q1: Why use swap for deletion?
oavoservice Explanation:
- Removing from middle of array is O(n).
- Swapping with last element allows O(1) pop.
- Does not affect randomness as order doesn't matter.
Q2: How to ensure uniform distribution?
oavoservice Explanation:
random.choice()uses uniform distribution.- Key is maintaining a contiguous array.
Q3: What if duplicate elements are allowed?
oavoservice Suggestion:
- Use
index_mapstoringsetof indices:{val: {idx1, idx2}}. RandomizedCollectionvariation.
💼 How oavoservice Helps with TikTok Interviews
Multiple Solutions - Basic to advanced Trade-off Analysis - Pros/cons comparison Extension Discussion - Duplicates, weighted variants Code Optimization - Efficient implementation
Contact oavoservice for professional data structure interview assistance!
Tags: #TikTok #DataStructure #RandomizedSet #HashMap #VOHelp #InterviewPrep #1point3acres
Need real interview questions? Contact WeChat Coding0201 immediately to get real questions.