Implement Dynamic Bitwise Masking and Uniform O(1) Set
Data Structure DesignModel answerLast 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: Addsvalto the structure if it is not already present. ReturnsTrueif added, orFalseif it was already contained.delete(val: int) -> bool: Removesvalif present. ReturnsTrueif successfully removed, orFalseif 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_randomwill 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?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Strategy
Part 1: Repeated-Key Bitwise Masking
The XOR operation operates on individual bits and serves as its own inverse. For a character code $c$ and key character code $k$, computing $c \oplus k$ yields an encoded value. Repeating the same XOR operation with $k$ restores the original value $c$.
To handle key repetition, any index $i$ in message pairs with index $i \pmod m$ in secret (where $m = \text{len}(secret)$). We convert characters to their Unicode integer code points via ord(), perform the XOR, and convert the resulting code point back to a character via chr(). To avoid expensive string concatenation within a loop, we store intermediate characters in an array and apply "".join() at the end.
Part 2: Constant-Time Sampling Container
To satisfy expected $O(1)$ performance across add, delete, and fetch_random, we pair two core structures:
- Dynamic Array (
items): Holds the elements contiguously. This enables pick-by-index in $O(1)$ time by picking a random index in $[0, \text{len}(items) - 1]$. - Hash Dictionary (
index_map): Maps each inserted integer to its current index withinitems. This enables $O(1)$ membership checks and instant location lookup during deletion.
The Swap-and-Pop Deletion Technique
Standard array deletions at an arbitrary index require shifting all subsequent elements, taking $O(N)$ time. However, because set elements are unordered, we can avoid shifting entirely:
- Look up the index
idxof the target value inindex_map. - Swap the target value with the final element in
items. - Update
index_mapso the swapped final element reflects its new positionidx. - Remove the last element from
itemsviapop()(an $O(1)$ operation) and delete the target value fromindex_map.
Edge Case Consideration: When deleting the element that happens to be at the very end of items, the swapped element is the target itself. Updating index_map for the moved element before deleting the targeted element from index_map ensures correctness without needing conditional branches.
Python Code Implementation
import random
def mask_data(message: str, secret: str) -> str:
"""Applies a repeating-key XOR mask to the input message."""
if not secret:
raise ValueError("Secret key must not be empty.")
key_len = len(secret)
transformed_chars = [
chr(ord(char) ^ ord(secret[i % key_len]))
for i, char in enumerate(message)
]
return "".join(transformed_chars)
class ConstantTimeSet:
"""A randomized set providing expected O(1) time complexity for additions,
deletions, and uniform random sampling."""
def __init__(self):
self.items = []
self.index_map = {}
def add(self, val: int) -> bool:
"""Inserts an element into the set. Returns True if inserted, False if already present."""
if val in self.index_map:
return False
self.index_map[val] = len(self.items)
self.items.append(val)
return True
def delete(self, val: int) -> bool:
"""Removes an element from the set. Returns True if removed, False if missing."""
if val not in self.index_map:
return False
idx_to_remove = self.index_map[val]
last_element = self.items[-1]
# Relocate the tail item into the slot left by the target item
self.items[idx_to_remove] = last_element
self.index_map[last_element] = idx_to_remove
# Remove the target item from both structures
self.items.pop()
del self.index_map[val]
return True
def fetch_random(self) -> int:
"""Returns an element picked uniformly at random from the set."""
if not self.items:
raise RuntimeError("Cannot fetch random element from an empty set.")
return random.choice(self.items)
Complexity Analysis
| Operation | Time Complexity | Space Complexity | Explanation |
|---|---|---|---|
mask_data | $\mathcal{O}(N)$ | $\mathcal{O}(N)$ | Performs constant-time XOR for each of the $N$ characters; creates a list of length $N$. |
add | $\mathcal{O}(1)$ amortized | $\mathcal{O}(1)$ | Hash lookup takes expected $\mathcal{O}(1)$; dynamic array append takes amortized $\mathcal{O}(1)$. |
delete | $\mathcal{O}(1)$ average | $\mathcal{O}(1)$ | Hash lookup, tail element relocation, and array pop() all run in constant average time. |
fetch_random | $\mathcal{O}(1)$ | $\mathcal{O}(1)$ | Array access by random index runs in deterministic constant time. |
Follow-ups & Advanced Considerations
Cryptographic Weakness of Multi-Byte XOR Masking
The repeated-key XOR cipher in Part 1 is structural equivalent to a polyalphabetic substitution cipher (such as the Vigenère cipher).
- Frequency Analysis: If key length $K$ is deduced (e.g., via Kasiski examination or Index of Coincidence), the ciphertext can be split into $K$ independent single-byte XOR streams. Each stream can be cracked individually by matching character frequency distributions against target language profiles.
- Malleability: XOR masking provides no data integrity or authenticity guarantees. An adversary can manipulate bits in transit ($C' = C \oplus M$), predictably altering the resulting plaintext upon decryption.
- Production Alternatives: Production systems requiring confidentiality and authentication should use standardized Authenticated Encryption with Associated Data (AEAD) schemes, such as AES-GCM or ChaCha20-Poly1305.