← 返回博客列表
TikTok

TikTok Interview: Design Randomized Set O(1)

2025-11-06

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:

  1. insert(val) - Insert element, return true if not present.
  2. remove(val) - Remove element, return true if present.
  3. search(val) - Check if element exists.
  4. getRandom() - Return a random element.

Constraint: Probability of each element being returned must be equal.

🎯 Core Challenges

  1. O(1) Insert/Delete - Fast location required
  2. O(1) Random Access - Index access needed
  3. Equal Probability - Ensure fairness
  4. 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:

Q2: How to ensure uniform distribution?

oavoservice Explanation:

Q3: What if duplicate elements are allowed?

oavoservice Suggestion:

💼 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.