KatInterview

Implement Dynamic Bitwise Masking and Uniform O(1) Set

Data Structure DesignModel answer
MediumModel answerData Structure DesignArraysHash MapBit Manipulation

Last updated

Construct an XOR string transformation function alongside an expected constant-time randomized container structure.

This task consists of two distinct components:

Part 1: Repeated-Key XOR Masking

Write a function mask_data(message: str, secret: str) -> str that applies a bitwise XOR transformation between the character codes of message and secret. If secret is shorter than message, the characters of secret must repeat cyclically. Return the transformed string produced by converting the resulting numerical values back to characters.

Part 2: Constant-Time Sampling Set

Design a data structure ConstantTimeSet that manages unique integer values and guarantees expected $O(1)$ time for the following operations:

  • add(val: int) -> bool: Adds val to the structure if it is not already present. Returns True if added, or False if it was already contained.
  • delete(val: int) -> bool: Removes val if present. Returns True if successfully removed, or False if it was missing.
  • fetch_random() -> int: Returns an element selected uniformly at random from the currently stored set. Each stored element must have equal probability of selection.

Examples

# Part 1: Masking
mask_data("hello", "abc")
# Character transformations:
# 'h' ^ 'a', 'e' ^ 'b', 'l' ^ 'c', 'l' ^ 'a', 'o' ^ 'b'

# Part 2: Container
cts = ConstantTimeSet()
cts.add(10)          # returns True
cts.delete(20)       # returns False
cts.add(20)          # returns True
cts.fetch_random()   # returns either 10 or 20 with equal probability
cts.delete(10)       # returns True
cts.fetch_random()   # returns 20

Constraints

  • $1 \le \text{len}(message) \le 10^5$
  • $1 \le \text{len}(secret) \le 10^5$
  • All inserted integer values fit in a signed 32-bit integer range.
  • fetch_random will only be invoked when the set contains at least one item.

Hints

Hint 1

Recall that the bitwise XOR operation satisfies $A \oplus B = C \iff C \oplus B = A$. Think about how index modulo arithmetic can map a shorter key over a longer payload.

Hint 2

No single standard data structure provides both $O(1)$ indexed lookup and $O(1)$ arbitrary deletion. How can you pair a dynamic array with a dictionary to achieve both?

Hint 3

When removing an arbitrary index from a contiguous array, shifting elements takes linear time. Can you replace the target index with the array's tail element to avoid shifts?