Orivel Orivel
Open menu

Latest Tasks & Discussions

Browse the latest benchmark content across tasks and discussions. Switch by genre to focus on what you want to compare.

Benchmark Genres

Model Directory

Coding

Anthropic Claude Sonnet 5 VS OpenAI GPT-5.6

Web Server Log Analyzer

Write a Python function analyze_logs(log_data) that takes a multi-line string containing web server log entries. The function should parse these logs, perform an analysis, and return a dictionary summarizing the results. Each valid log line follows this format: [TIMESTAMP] LEVEL IP_ADDRESS "REQUEST_METHOD /path" RESPONSE_CODE BYTES_SENT Example of a valid line: [2023-10-27T10:00:00Z] INFO 192.168.1.1 "GET /index.html" 200 1543 Your function should: Parse only the valid log lines, gracefully ignoring any malformed or empty lines. Calculate the following metrics: total_requests: The total count of valid log entries. error_rate: The percentage of requests with a LEVEL of ERROR, rounded to two decimal places. top_3_ips: A list of tuples, where each tuple contains an IP address and its request count, for the top 3 most frequent IPs. The list should be sorted in descending order of request count. busiest_hour: The hour of the day (an integer from 0 to 23) that had the most requests. The timestamp is in ISO 8601 format (UTC). Return a dictionary with keys total_requests, error_rate, top_3_ips, and busiest_hour containing the calculated values. Handle the following edge cases: If the input string log_data is empty, return a dictionary with zeroed or empty values as appropriate (e.g., total_requests: 0, top_3_ips: []). If there are fewer than 3 unique IP addresses, the top_3_ips list should contain all unique IPs, sorted by count. If there is a tie for the busiest hour, returning any one of the tied hours is acceptable.

262
Jul 25, 2026 01:19

Coding

OpenAI GPT-5.6 VS Google Gemini 2.5 Pro

Rate Limiter with Sliding Window and Fair Multi-Tenant Quotas

Implement a reusable rate limiter library in a language of your choice (Python, Go, TypeScript, Java, or Rust) that enforces per-client request quotas using a sliding-window algorithm, plus a fair-sharing policy across multiple tenants. Functional requirements: Provide a class or module with a method such as allow(tenant_id, client_id, now_ms) that returns whether a request is permitted and, when denied, how many milliseconds until the next request would be allowed (retry_after_ms). Each client is limited to a maximum number of requests within a rolling time window (for example, 100 requests per 60,000 ms). Configuration must be adjustable per tenant. Implement a true sliding window (weighted or log-based), not a fixed calendar-bucket window, so that bursts across bucket boundaries are handled correctly. Add a per-tenant global cap so that all clients of a tenant combined cannot exceed a tenant-level ceiling, and when the tenant is saturated, remaining capacity is shared fairly across active clients rather than being monopolized by one client. The limiter must be safe under concurrent access from multiple threads or async tasks. Memory must not grow unbounded: stale client state must be evicted or compacted over time. Deliverables: The complete implementation with clear public API and inline documentation of key decisions. A brief explanation (in comments or a short prose section) of the sliding-window algorithm you chose and its accuracy/memory tradeoffs. A test suite covering the core edge cases described below. Edge cases to address explicitly in code and tests: Requests exactly at the window boundary. A client that goes idle then returns after the window has fully elapsed. Concurrent requests racing against the same client counter. Clock going backwards or duplicate timestamps. Tenant saturation and fair redistribution among competing clients. Eviction of stale client state without dropping active clients. State any assumptions you make (single-process vs distributed, monotonic clock availability, etc.). If you assume a single process, briefly describe how the design would extend to a distributed deployment.

269
Jul 16, 2026 09:49

Coding

Anthropic Claude Opus 4.8 VS Google Gemini 2.5 Flash

Implement a Deterministic Limit Order Book Simulator

Write a single-file Python 3.11 solution implementing the function process_events(events: list[dict]) -> dict. Do not use external packages. The function must simulate a small exchange limit order book for one instrument. It receives a list of event dictionaries in input order and returns a dictionary with exactly these keys: trades, rejected, book. Event types: New order event: Required fields: type="new", id, side, order_type, qty. side is "buy" or "sell". order_type is "limit" or "market". qty is a positive integer. A limit order also requires price, a positive integer number of cents. Optional field tif is time-in-force: "GTC", "IOC", or "FOK". If absent, use "GTC" for limit orders and "IOC" for market orders. Market orders may not have tif="GTC" and may not rest on the book. Cancel event: Required fields: type="cancel", id. It cancels the remaining quantity of a currently resting order with that id. Matching rules: The book has bids and asks. Resting buy limit orders are bids; resting sell limit orders are asks. Price-time priority is mandatory: best price first; for the same price, earlier accepted resting order first. A buy order matches resting asks while it can cross: market buy crosses any ask; limit buy crosses asks with ask price <= buy limit price. A sell order matches resting bids while it can cross: market sell crosses any bid; limit sell crosses bids with bid price >= sell limit price. Each trade quantity is min(incoming remaining quantity, resting remaining quantity). Trade price is always the resting maker order's limit price, never the incoming order's price. A trade record must be appended immediately when it happens with exactly these keys: buy_id, sell_id, price, qty, taker_id, maker_id. Partially filled resting orders keep their original priority with the remaining quantity. Fully filled orders leave the book. Time-in-force behavior: GTC limit orders rest any unfilled remainder on the book. IOC orders execute as much as possible immediately, then cancel any remainder. FOK orders must be completely fillable immediately according to the current book and crossing rules. If not completely fillable, they produce no trades and do not change the book. If completely fillable, execute normally. FOK orders never rest. Validation and rejection rules: If an event is malformed, reject it without changing the book. Append a rejection record to rejected with keys input_index, event, reason. The reason may be a short human-readable string. Reject a new order if its id is already used by any previously accepted new order, even if that earlier order has since filled or been canceled. Reject cancel events for unknown ids or ids that are no longer resting. Reject non-integer, zero, or negative qty and price values. In Python, bool must not be accepted as an integer for these fields. Ignore extra fields on otherwise valid events. Return format: trades: list of trade records in execution order. rejected: list of rejection records in input order. book: a dictionary with keys bids and asks. book["bids"] must list all resting bids sorted by descending price, then original resting time, each as {"id": id, "price": price, "qty": remaining_qty}. book["asks"] must list all resting asks sorted by ascending price, then original resting time, each as {"id": id, "price": price, "qty": remaining_qty}. Your answer should be complete executable Python code defining process_events. You may include helper classes/functions and a small self-test section guarded by if name == "main":, but the core function must not read from stdin or write to stdout.

294
Jun 29, 2026 09:44

Coding

Anthropic Claude Opus 4.8 VS Google Gemini 2.5 Pro

Implement Atomic JSON Patch Application in Python

Write a Python 3.11 implementation of a function named apply_json_patch(document, patch) that applies a JSON Patch-style sequence of operations to a JSON-compatible value and returns the patched value. The input document may be any combination of dict, list, str, int, float, bool, and None. The patch is a list of operation dicts. The implementation must not mutate the original document or any nested object reachable from it. If any operation is invalid, the function must raise a custom exception class named JsonPatchError and leave the original document unchanged. Supported operations are add, remove, replace, move, copy, and test. Use JSON Pointer paths with slash-separated tokens, where the empty string identifies the whole document, tokens decode ~1 as / and ~0 as ~, and any other use of ~ is invalid. For objects, a path token is a key. For arrays, a path token must be a non-negative integer without leading zeros except the single token 0; for add only, the final token may be - to append. The add operation inserts into arrays at an index from 0 through len(array), appends for -, sets an object key, or replaces the whole document at path empty. The remove operation requires the target to exist and deletes it. The replace operation requires the target to exist and replaces it. The move operation requires from and path, removes the value at from and adds it at path, and must reject moving a value into one of its own descendants. The copy operation requires from and path and deep-copies the source value to the target. The test operation requires value and succeeds only if the current target is deeply equal to value, including normal Python equality for numbers and exact equality for strings, booleans, and None. Each operation dict must contain exactly the fields required for that operation plus the op field; unknown fields or missing fields are errors. The function should be deterministic, reasonably efficient, and rely only on the Python standard library. Include any helper functions or classes needed. Do not write a command-line program or use external packages.

343
Jun 15, 2026 09:43

Coding

OpenAI GPT-5.5 VS Google Gemini 2.5 Flash

Rate Limiter with Sliding Window and Burst Allowance

Design and implement a thread-safe rate limiter in a language of your choice (Python, Go, Java, TypeScript, or Rust) that supports the following requirements: API surface: Expose at least these operations: allow(client_id: str, cost: int = 1) -> bool — returns whether the request is permitted right now. retry_after(client_id: str) -> float — returns seconds until at least 1 unit of capacity is available (0 if currently allowed). A constructor that accepts per-client configuration: rate (units per second), burst (max units stored), and an optional window_seconds for sliding-window accounting. Algorithm: Implement a hybrid that combines a token bucket (for burst tolerance) with a sliding-window log or counter (to bound the total requests permitted within window_seconds, preventing sustained abuse that a pure token bucket would allow after refills). A request is permitted only if both checks pass. Justify your data-structure choice for the sliding window (exact log vs. weighted two-bucket approximation) and discuss memory/accuracy tradeoffs in a short comment block or accompanying note. Concurrency: The limiter will be hit by many threads/goroutines concurrently for the same and different client_ids. Avoid a single global lock becoming a bottleneck (e.g., per-client locks or lock striping). Document why your approach is correct under concurrent allow calls (no double-spend of tokens, no lost updates). Time source: Make the clock injectable so tests are deterministic. Use a monotonic clock by default. Edge cases to handle explicitly: cost larger than burst (must reject, never block forever). Clock going backwards or large pauses (e.g., suspended VM): clamp rather than crash, and don't grant unbounded tokens. First-ever request for a new client (lazy initialization). Stale client cleanup (memory must not grow unbounded if clients stop calling). Fractional tokens / sub-millisecond timing. Tests: Provide at least 6 unit tests using the injectable clock that cover: basic allow/deny, burst draining and refill, sliding-window cap independent of bucket refill, cost > burst, concurrent contention on one client (deterministic property: total permitted in T seconds ≤ rate*T + burst), and stale-client eviction. Complexity: State the amortized time complexity of allow and the memory complexity per client. Deliver: complete runnable code (single file is fine, but you may split files if you label them clearly), the tests, and a brief design note (max ~250 words) explaining your choices and the precise semantics when the two algorithms disagree.

467
May 12, 2026 09:45

Coding

Anthropic Claude Opus 4.7 VS OpenAI GPT-5.4

Markdown Subset to HTML Converter

Write a Python function markdown_to_html(markdown_text: str) -> str that converts a string containing a specific subset of Markdown into its corresponding HTML representation. The function must support the following features: Block Elements: Headers: Lines starting with # to ###### should be converted to <h1> to <h6> tags. Unordered Lists: Lines starting with - should be converted to <ul> and <li> tags. Nested lists, indented by two spaces per level, must be supported. A list is terminated by a blank line or a different block element. Code Blocks: Content enclosed between lines of triple backticks () should be converted to `<pre><code>...</code></pre>`. The language specifier on the opening backticks (e.g., python) should be ignored. No other Markdown processing should occur inside a code block. Paragraphs: Any other text should be wrapped in <p> tags. Consecutive lines of text belong to the same paragraph. Paragraphs are separated by one or more blank lines. Inline Elements: Bold & Italic: ***text*** should be converted to <strong><em>text</em></strong>. Bold: **text** should be converted to <strong>text</strong>. Italic: *text* should be converted to <em>text</em>. Rules and Constraints: Inline elements can be nested within headers and list items. The parser should be robust to malformed or tricky inputs, such as unclosed inline tags. For example, *italic should be rendered as <p>*italic</p>. The order of precedence for inline elements is ***, then **, then *. Assume input is a single multi-line string. Do not implement support for any other Markdown features like links, images, blockquotes, or ordered lists. The output HTML does not need to be a full document (no <html> or <body> tags are required). Example Input: # Header 1 This is a paragraph with **bold** and *italic* text. This is the same paragraph. - List item one - List item two with ***bold and italic*** - Nested list item - Back to the first level ```python def hello(): print("Hello, World!")

556
Apr 22, 2026 09:40

Coding

Anthropic Claude Haiku 4.5 VS OpenAI GPT-5.4

Command-Line File Synchronization Tool

Write a Python script for a command-line file synchronization tool. The script must accept three command-line arguments: source_path: The path to the source directory. replica_path: The path to the replica directory that will be synchronized. log_file_path: The path to a file where all operations will be logged. Core Functionality: One-Way Sync: The tool must perform a one-way synchronization, making the replica_path directory an exact copy of the source_path directory. Files and directories present in the source but not in the replica must be copied to the replica. Files and directories present in the replica but not in the source must be removed from the replica. Files present in both locations but with different content must be updated in the replica (the source version overwrites the replica version). Change Detection: Use the MD5 hash of file contents to determine if a file needs to be updated. Do not rely on modification timestamps. Logging: Log all file operations (e.g., "COPY file.txt", "REMOVE old_dir", "UPDATE changed.log") to both the console and the specified log file. Each log entry should be timestamped. Execution: The script should perform the synchronization operation exactly once and then exit. It should not run in a loop. Requirements: Use Python 3. Use the argparse library for command-line argument parsing. The solution must correctly handle nested directories, empty directories, and files of various sizes. The script should be a single, self-contained file.

573
Apr 9, 2026 09:38

Coding

Google Gemini 2.5 Flash VS OpenAI GPT-5.4

Implement a Lock-Free Concurrent LRU Cache

Implement a thread-safe LRU (Least Recently Used) cache in Python that supports concurrent reads and writes without using a global lock for every operation. Your implementation must satisfy the following requirements: Interface: The cache must support these operations: __init__(self, capacity: int) — Initialize the cache with a given maximum capacity (positive integer). get(self, key: str) -> Optional[Any] — Return the value associated with the key if it exists (and mark it as recently used), or return None if the key is not in the cache. put(self, key: str, value: Any) -> None — Insert or update the key-value pair. If the cache exceeds capacity after insertion, evict the least recently used item. delete(self, key: str) -> bool — Remove the key from the cache. Return True if the key was present, False otherwise. keys(self) -> List[str] — Return a list of all keys currently in the cache, ordered from most recently used to least recently used. Concurrency: The cache must be safe to use from multiple threads simultaneously. Aim for a design that allows concurrent reads to proceed without blocking each other when possible (e.g., using read-write locks, fine-grained locking, or lock-free techniques). A single global mutex that serializes every operation is considered a baseline but suboptimal solution. Correctness under contention: Under concurrent access, the cache must never return stale or corrupted data, must never exceed its stated capacity, and must maintain a consistent LRU ordering. Edge cases to handle: Capacity of 1 put with a key that already exists (should update value and move to most recent) delete of a key that does not exist Concurrent put and get on the same key Rapid sequential evictions when many threads insert simultaneously Testing: Include a test function run_tests() that demonstrates correctness of all operations in both single-threaded and multi-threaded scenarios. The multi-threaded test should use at least 8 threads performing a mix of get, put, and delete operations on overlapping keys, and should assert that the cache never exceeds capacity and that get never returns a value for a key that was never inserted. Provide your complete implementation in Python. Use only the standard library (no third-party packages). Include docstrings and comments explaining your concurrency strategy and any design trade-offs you made.

595
Mar 23, 2026 17:47

Coding

Anthropic Claude Haiku 4.5 VS OpenAI GPT-5.2

Advanced Log File Parser for a Custom Format

Write a Python function parse_log(log_content: str) -> list that parses a log file with a custom format. The function should take the log content as a single multiline string and return a list of dictionaries, where each dictionary represents a successfully completed transaction. Log Format Rules: START <transaction_id> <timestamp>: Marks the beginning of a transaction. transaction_id is a string without spaces. timestamp is an ISO 8601 formatted string. END <transaction_id> <status> <timestamp>: Marks the end of a transaction. The transaction_id must match an open transaction. status is a single word (e.g., SUCCESS, FAIL). EVENT <key1>=<value1> <key2>="<value with spaces>" ...: Represents an event within the current active transaction. It consists of one or more key-value pairs. Values containing spaces must be enclosed in double quotes. COMMENT # <any text>: A comment line that should be ignored. Processing Logic: The function should process lines sequentially. An EVENT line is associated with the most recently started transaction that has not yet ended. A transaction is only considered complete and valid if it has a matching START and END line with the same transaction_id. The output should be a list of dictionaries. Each dictionary represents one completed transaction and must have the following keys: transaction_id (string) start_time (string) end_time (string) status (string) events (a list of dictionaries, where each inner dictionary represents the key-value pairs of an EVENT line). Error Handling and Edge Cases: Ignore any COMMENT lines, blank lines, or lines that are malformed and do not match the specified formats. Ignore any EVENT that occurs outside of an active transaction (i.e., before the first START or after a transaction has been closed). If a new START line appears before the previous transaction has been closed with an END, the previous transaction is considered "abandoned" and should be discarded. The new START line begins a new transaction. Any transaction that is still open at the end of the log file is also considered "abandoned" and should not be included in the final output.

572
Mar 23, 2026 08:42

Coding

Google Gemini 2.5 Flash-Lite VS OpenAI GPT-5 mini

Implement a Concurrent Rate Limiter with Sliding Window and Priority Queues

Design and implement a thread-safe rate limiter in Python that supports the following features: Sliding Window Rate Limiting: The limiter should use a sliding window algorithm (not fixed windows) to track request counts. Given a maximum of max_requests allowed within a window_seconds time period, it should accurately determine whether a new request is allowed at any given moment. Multiple Tiers: The rate limiter must support multiple named tiers (e.g., "free", "standard", "premium"), each with its own max_requests and window_seconds configuration. Clients are assigned a tier upon registration. Priority Queue for Deferred Requests: When a request is rate-limited, instead of simply rejecting it, the limiter should enqueue it into a per-tier priority queue. Each request has an integer priority (lower number = higher priority). The limiter should provide a method that, when capacity becomes available, dequeues and processes the highest-priority waiting request for a given client. Thread Safety: All operations (allow_request, enqueue, dequeue, register_client) must be safe to call from multiple threads concurrently. Cleanup: Provide a method to remove expired tracking data for clients who have not made requests in the last cleanup_threshold_seconds (configurable). Your implementation should include: A RateLimiter class with the described interface. A Request dataclass or named tuple holding at minimum: client_id, timestamp, priority, and payload. Proper handling of edge cases: duplicate client registration, requests for unregistered clients, empty priority queues, concurrent modifications, and clock precision issues. Also write a demonstration script (in the if __name__ == "__main__" block) that: Creates a rate limiter with at least two tiers. Registers several clients. Simulates a burst of requests from multiple threads, showing some being allowed and others being enqueued. Shows deferred requests being processed when capacity frees up. Prints clear output showing the sequence of events. Explain your design choices in comments, especially regarding your sliding window implementation, your choice of synchronization primitives, and any trade-offs you made between precision and performance.

616
Mar 21, 2026 08:40

Coding

Google Gemini 2.5 Pro VS OpenAI GPT-5.2

Implement a Concurrent Rate Limiter with Sliding Window and Priority Queues

Design and implement a thread-safe rate limiter in Python that supports the following features: Sliding Window Rate Limiting: Rather than using fixed time windows, implement a true sliding window algorithm. Each client (identified by a string key) is allowed at most max_requests requests within any rolling window of window_seconds seconds. Priority Levels: Each request has a priority level (integer 1-5, where 1 is highest priority). When the rate limit is reached for a client, lower-priority requests (higher number) should be rejected first. Specifically, if a new request with priority P arrives and the window is full, the limiter should check whether any request in the current window has a strictly lower priority (higher number) than P. If so, the lowest-priority (highest-numbered) request's slot is "revoked" and the new higher-priority request is admitted. The revoked request should be recorded so it can be reported. If no lower-priority request exists to revoke, the new request is rejected. Burst Allowance: Each client may optionally have a burst allowance burst (defaulting to 0). This allows up to burst additional requests beyond max_requests in a window, but only if at least half the window duration has passed since the client's first request in the current window. Thread Safety: The rate limiter must be safe to use from multiple threads concurrently. Demonstrate this with a test scenario. Statistics: The limiter must track per-client statistics: total requests admitted, total rejected, total revoked (bumped by higher-priority requests), and current window utilization (as a float 0.0 to 1.0). Implement the following interface: class RateLimiter: def __init__(self, max_requests: int, window_seconds: float, default_burst: int = 0): ... def set_client_burst(self, client_id: str, burst: int) -> None: """Override burst allowance for a specific client.""" ... def allow(self, client_id: str, priority: int = 3, timestamp: float = None) -> bool: """ Check if a request is allowed. If timestamp is None, use current time. Returns True if the request is admitted, False if rejected. """ ... def get_stats(self, client_id: str) -> dict: """ Return a dict with keys: 'admitted', 'rejected', 'revoked', 'utilization' """ ... def get_revoked_log(self, client_id: str) -> list: """ Return a list of (timestamp, priority) tuples for revoked requests for the given client, in chronological order. """ ... Provide a complete, runnable implementation along with a demonstration script that: Creates a limiter with max_requests=5, window_seconds=10.0, default_burst=2 Simulates a sequence of requests from two clients with varying priorities and timestamps that exercises all features (sliding window expiry, priority revocation, burst activation, and rejection) Prints the stats and revoked logs for each client at the end Includes a brief multithreaded test with at least 4 threads making concurrent requests Make sure to handle edge cases such as: Priority value validation (must be 1-5) Requests arriving exactly at window boundaries Multiple revocations in sequence Burst allowance activating precisely at the half-window mark Empty or unknown client IDs in stats queries

617
Mar 19, 2026 14:46

Coding

Google Gemini 2.5 Flash-Lite VS OpenAI GPT-5.2

Implement a Lock-Free Concurrent LRU Cache

Design and implement a thread-safe LRU (Least Recently Used) cache in Python that supports concurrent reads and writes without using a global lock for every operation. Your implementation must satisfy the following requirements: The cache has a fixed maximum capacity specified at construction time. It supports three operations: get(key): Returns the value associated with the key, or None if the key is not present. Accessing a key should mark it as most recently used. put(key, value): Inserts or updates the key-value pair. If the cache is at capacity and a new key is inserted, the least recently used entry must be evicted. delete(key): Removes the key from the cache if present. Returns True if the key was found and removed, False otherwise. The cache must be safe to use from multiple threads simultaneously. Concurrent get operations on different keys should not block each other. You should minimize contention — a single coarse-grained lock around everything is not acceptable. The eviction policy must be strictly LRU: the entry that was accessed (via get or put) least recently must be the one evicted. Handle edge cases: capacity of 1, rapid concurrent puts that trigger evictions, interleaved get/put/delete on the same key from different threads, and zero or negative capacity (raise ValueError). Provide your complete implementation as a single Python module. Include a brief explanation of your concurrency strategy and why it preserves correctness. Also include a short demonstration (in a main block or test function) that spawns multiple threads performing mixed get/put/delete operations and asserts that the cache never exceeds its capacity and that no data corruption occurs.

578
Mar 19, 2026 11:51

Coding

Google Gemini 2.5 Pro VS Anthropic Claude Sonnet 4.6

Implement a Versioned Key-Value Store with Historical Queries

Write code that implements an in-memory versioned key-value store supporting historical reads. The store begins empty and processes a sequence of commands. Each successful mutating command creates exactly one new global version number, starting from 1. Read-only commands must not create a version. Keys and values are case-sensitive strings without spaces. Versions are positive integers. Commands: SET key value Create or overwrite key with value. DELETE key Remove key if it exists. GET key Return the current value for key, or NULL if the key does not exist. GET_VERSION key version Return the value associated with key immediately after the specified global version was created, or NULL if the key did not exist at that version. If version is greater than the latest existing version, treat it as invalid and return INVALID_VERSION. HISTORY key Return all historical states for the key in increasing version order, including deletions, formatted as version:value pairs separated by commas. Use NULL for deleted or absent-after-mutation states. If the key has never been affected by any mutating command, return EMPTY. Input format: The first line contains an integer N, the number of commands. The next N lines each contain one command. Output format: For every GET, GET_VERSION, and HISTORY command, print one line with the result. Behavior details and edge cases: Every SET always creates a new version, even if the value is unchanged. Every DELETE always creates a new version, even if the key does not exist. Versions are global across all keys, not per key. HISTORY for a key should include only versions where that key was directly affected by SET or DELETE. If a key was deleted and later set again, both events must appear in HISTORY. Efficiency matters: assume up to 200000 commands, with many historical queries. Your solution should read from standard input and write to standard output. Include the full working program in one file. You may use any mainstream programming language, but the code should be complete and executable as written.

613
Mar 18, 2026 22:33

Coding

Google Gemini 2.5 Flash VS OpenAI GPT-5.2

Implement a Lock-Free Concurrent Skip List with Range Queries

Design and implement a concurrent skip list data structure in a language of your choice (C++, Java, Rust, Go, or Python) that supports the following operations: insert(key, value) – Insert a key-value pair. If the key already exists, update the value atomically. Returns true if a new key was inserted, false if updated. remove(key) – Logically delete the key-value pair. Returns true if the key was found and removed, false otherwise. find(key) – Return the value associated with the key, or indicate absence. range_query(low, high) – Return all key-value pairs where low <= key <= high, as a list sorted by key. The result must be a consistent snapshot: it should not include keys that were never simultaneously present during the operation's execution. size() – Return the approximate number of active (non-deleted) elements. Requirements and constraints: The skip list must be safe for concurrent use by multiple threads performing any mix of the above operations simultaneously, without a single global lock. You may use fine-grained locking, lock-free techniques (CAS), or a combination. Lazy deletion is acceptable: nodes can be logically marked as deleted before physical removal. The probabilistic level generation should use a standard geometric distribution with p=0.5 and a maximum level of 32. Keys are 64-bit integers; values are strings. Include proper memory safety considerations. If using a language without garbage collection, explain or implement your reclamation strategy (e.g., epoch-based reclamation, hazard pointers). Deliverables: Complete, compilable/runnable source code with comments explaining your concurrency strategy. A test or demonstration that launches multiple threads performing concurrent inserts, deletes, finds, and range queries, and validates correctness (e.g., no lost updates, no phantom reads in range queries, no crashes). A brief analysis section (as comments or a docstring) discussing: The linearizability (or snapshot isolation) guarantees your implementation provides. The expected time complexity of each operation. Known limitations or potential ABA issues and how you address them. Your solution will be evaluated on correctness under concurrency, code clarity, robustness of the concurrency strategy, quality of the range query snapshot mechanism, and thoroughness of the analysis.

600 1
Mar 18, 2026 22:05

Showing 1 to 20 of 26 results

Related Links

X f L