xAI logo

xAI Medium Interview Questions

8 medium-level practice questions for xAI technical interviews

xAI software engineer interviews cover algorithms, data structures, system design, and coding problems drawn from real interview rounds.

Software Engineer Backend Engineer Frontend Engineer Full Stack Engineer Mobile Engineer Data Engineer Data Scientist ML Engineer DevOps Engineer DevOps Engineer Product Manager SRE Security Engineer Engineering Manager Data Analyst UX/UI Designer QA Engineer
coding Medium Verified Question #1

1. Corrupted Sensor Detector


Category: Algorithm coding problem
You are managing a network of n environmental sensors labeled 0 to n - 1. Each sensor is either functioning correctly or corrupted, but you do...
Input: List
Output: Computed result
Want to practise this one?
Create a free account to open the full question and practise xAI questions with AI.
Sign up free
coding Medium dynamic programming #1

1. Dynamic Programming — Max Sum of Non-Adjacent Integers

Background: At xAI, handling data efficiently is crucial, especially when aggregating usages or transactions that can be fragmented across different user sessions. This problem can relate to optimizing user experience in analytics.
Problem statement: Given an array of integers nums, return the maximum sum of non-adjacent elements. Specifically, if you choose an element, you cannot choose the elements immediately before or after it.
Function/class signature:
  • def max_sum_non_adjacent(nums: List[int]) -> int:

Example 1:
  • Input: nums = [2, 4, 6, 2, 5]

  • Output: 13

  • Explanation: We can choose 2, 6, and 5, which give the sum of 13.

Example 2:
  • Input: nums = [1, 2, 3, 1]

  • Output: 4

  • Explanation: Choose 1 and 3.

Constraints:
  • 1 <= len(nums) <= 100

  • 0 <= nums[i] <= 400

Want to practise this one?
Create a free account to open the full question and practise xAI questions with AI.
Sign up free
coding Medium trie #2

2. Trie — Implement a trie-based tokenizer

Background: xAI often processes vast amounts of textual data from various sources. A trie-based tokenizer can efficiently manage and tokenize this data.
Problem statement: Implement a Tokenizer class that allows you to add words and tokenize sentences into a list of words. The tokenizer should be able to handle spaces and punctuation correctly. The key methods should utilize a trie data structure, which enables efficient storage and retrieval of words.
Function/class signature:
  • class Tokenizer:

  • def add_word(self, word: str) -> None:

  • def tokenize(self, sentence: str) -> List[str]:

Example 1:
Input: tokenizer = Tokenizer()
tokenizer.add_word("hello")
tokenizer.add_word("world")
output = tokenizer.tokenize("hello world!")
Output: ['hello', 'world']
Explanation: The method returns a list of words in the given sentence, excluding punctuation.
Example 2:
Input: tokenizer.tokenize("xAI is amazing.")
Output: ['xAI', 'is', 'amazing']
Constraints:
  • Words to be added will have a maximum length of 100 characters.

  • Sentences to be tokenized will contain at most 1000 characters.

  • The add_word and tokenize methods should operate efficiently for a large number of words.
coding Medium heap #3

3. Algorithms and Data Structures — Finding the kth largest element in a stream

Background: xAI's products may involve real-time processing of user-generated data streams. Efficiently handling large amounts of data in real-time is crucial for performance and user experience.
Problem statement: You need to implement a class KthLargest that keeps track of the kth largest element in a dynamically updating stream of integers. The class should support the method add(int val), which adds an integer to the stream and returns the current kth largest element.
Function/class signature:
  • class KthLargest:

  • def __init__(self, k: int, nums: List[int]) -> None:

  • def add(self, val: int) -> int:


Example 1:
Input: k = 3, nums = [4, 5, 8, 2]
KthLargest kthLargest = KthLargest(k, nums)
kthLargest.add(3)
Output: 4
Explanation: After adding 3, the third largest number is 4.
Example 2:
Input: kthLargest.add(5)
Output: 5
Explanation: The third largest number is 5.
Constraints:
  • 1 <= k <= 104

  • 0 <= nums.length <= 104

  • -104 <= nums[i] <= 104

  • -104 <= val <= 104

  • At most 104 calls will be made to add.


coding Medium array #4

4. CODING — Detecting Missing Values

Background: In the field of AI and data processing, handling missing data is crucial for ensuring the integrity of models. xAI, which leverages vast datasets for its AI solutions, needs robust methods to detect and fill missing values efficiently.
Problem statement: Create a function to detect and list the indices of missing values (represented as None) in an input list of integers. The function should return the indices of the None values in ascending order.
Function/class signature:
  • def find_missing_indices(data: List[Optional[int]]) -> List[int]:


Example 1:
  • Input: find_missing_indices([1, None, 3, None, 5])

  • Output: [1, 3]

  • Explanation: The missing values (None) are found at indices 1 and 3.


Example 2:
  • Input: find_missing_indices([None, None, 2, 4])

  • Output: [0, 1]

  • Explanation: The missing values are both found at the start of the list, at indices 0 and 1.


Constraints:
  • data will have at most 10^4 elements.

  • Each element can either be an integer or None.

  • The function should run in linear time complexity O(n).

coding Medium graph #5

5. Graph — Find the shortest path in a social network

Background: xAI focuses on understanding and modeling social interactions. This problem is relevant for designing features that analyze and recommend connections between users based on their interactions.
Problem statement: Given a social network represented as an undirected graph where nodes are users and edges are friendships, implement a function to find the shortest path between two users. You are to return the number of edges in the shortest path or -1 if no path exists.
Function/class signature:
  • def shortest_path(graph: List[List[int]], start: int, end: int) -> int:


Example 1:
Input:
graph = [[1, 2], [0, 2, 3], [0, 1], [1]],
start = 0,
end = 3
Output:
2
Explanation: The shortest path is 0 → 1 → 3.
Example 2:
Input:
graph = [[1], [0, 2], [1, 3], [2]],
start = 0,
end = 3
Output:
3
Explanation: The shortest path is 0 → 1 → 2 → 3.
Constraints:
  • 1 <= graph.length <= 1000

  • 0 <= start, end < graph.length

  • Each graph entry should have 0 <= graph[i].length <= 1000
system design Medium stack queue #6

6. Design GrokRequestBatcher — deterministic, model-aware inference batching


Background
xAI's Grok inference service needs to combine compatible requests into batches while balancing throughput and waiting time. An anonymous xAI interview report described completing a Python function for batching language-model requests; this exercise adapts that reported task into a self-contained class design. The scheduling rules below are exercise specifications, not claims about xAI's production implementation.
Requirements
1. Maintain pending requests in insertion order. Each request has an ID, an opaque model key, a positive token reservation, an arrival time, and a time-to-live. A batch must contain requests for exactly one model and must respect both the configured token and request-count limits.
2. Every public operation receives now_ms. Before performing that operation, remove every request whose expiration time is at most now_ms. Expiration is arrival_ms + ttl_ms. Time is nondecreasing across calls, and expiration takes precedence over selection or cancellation.
3. submit returns false if its ID is already pending after expiration cleanup; otherwise it appends the request and returns true. Duplicate submissions must not update the existing request. An ID may be reused after its request expires, is canceled, or is dispatched.
4. A model is ready if any of these conditions holds after cleanup: its total pending token reservations are at least max_tokens; its pending request count is at least max_requests; or its oldest pending request has waited at least max_wait_ms. Among ready models, choose the model whose oldest pending request was inserted earliest. Insertion order, not model-name order, breaks equal-arrival-time ties.
5. next_batch removes and returns exactly one batch for the selected model. Take the longest nonempty prefix of that model's insertion-ordered queue that fits both limits. Stop at the first request that would exceed a limit: do not skip it to fit smaller requests behind it. If no model is ready, return an empty list. A readiness threshold is based on the entire model queue, even when only a short prefix fits.
6. Support cancellation by ID and inspection of pending IDs in global insertion order. All operations are single-threaded; no background timer, inference execution, networking, or persistence is required.
Class API
  • GrokRequestBatcher(max_tokens: int, max_requests: int, max_wait_ms: int) — construct an empty batcher with fixed limits.

  • submit(request_id: str, model: str, tokens: int, now_ms: int, ttl_ms: int) -> bool — clean up expired requests, then attempt to enqueue a request.

  • cancel(request_id: str, now_ms: int) -> bool — clean up expired requests, then remove the specified pending request; return whether it existed.

  • next_batch(now_ms: int) -> list[str] — clean up expired requests, select one ready model, and return dispatched IDs in that model's queue order.

  • pending(now_ms: int) -> list[str] — clean up expired requests and return all remaining IDs in global insertion order.


Example 1:
Input sequence, using opaque model key text:
{
  "config": {"max_tokens": 10, "max_requests": 3, "max_wait_ms": 50},
  "calls": [
    ["submit", "a", "text", 6, 0, 100],
    ["submit", "b", "text", 5, 1, 100],
    ["submit", "c", "text", 4, 2, 100],
    ["next_batch", 2],
    ["next_batch", 3],
    ["next_batch", 51],
    ["pending", 51]
  ]
}

Output, one result per call:
[true, true, true, ["a"], [], ["b", "c"], []]

Explanation: At time 2, text is ready because its total reservation is 6 + 5 + 4 = 15 >= 10 and its count is 3. The batch contains only a: adding b would use 11 tokens, and skipping b to include c is forbidden. At time 3, the remaining total is 9 and the oldest request has waited only 2 ms. At time 51, b has waited exactly 50 ms, so b and c dispatch together.
Example 2:
Input sequence:
{
  "config": {"max_tokens": 8, "max_requests": 2, "max_wait_ms": 20},
  "calls": [
    ["submit", "x", "text", 3, 0, 10],
    ["submit", "y", "vision", 4, 1, 100],
    ["submit", "z", "vision", 4, 2, 100],
    ["next_batch", 2],
    ["submit", "w", "text", 5, 3, 100],
    ["cancel", "w", 4],
    ["pending", 10],
    ["cancel", "x", 10],
    ["submit", "x", "text", 8, 10, 5],
    ["submit", "x", "text", 1, 10, 100],
    ["next_batch", 10]
  ]
}

Output:
[true, true, true, ["y", "z"], true, true, [], false, true, false, ["x"]]

Explanation: At time 2, only vision is ready: its two requests reserve 4 + 4 = 8 tokens. The older text request does not block it. Request w is canceled, and the original x expires exactly at time 10. Its ID can then be reused. The second submission of the new x is rejected without changing its 8-token reservation, so it dispatches immediately.
Constraints
  • 1 <= max_tokens <= 1,000,000, 1 <= max_requests <= 1,000, and 0 <= max_wait_ms <= 1,000,000.

  • At most 2,000 requests are pending at once, with at most 10,000 public method calls per instance. An O(n) operation is acceptable for this exercise.

  • IDs and model keys are nonempty strings of at most 100 characters. Every submitted reservation satisfies 1 <= tokens <= max_tokens; 1 <= ttl_ms <= 1,000,000.

  • Timestamps are nonnegative integers and are nondecreasing across all calls, including unsuccessful submissions and cancellations. Inputs satisfy these bounds.
system design Medium api design #7

7. Design UserSessionManager — A class to manage user sessions in an online platform

1. Background: The UserSessionManager class is critical for xAI to handle user sessions securely and efficiently. It requires proper management of user logins, session timeouts, and session validation to ensure a consistent user experience across devices.
2. Requirements:
1. The class should allow user logins and logouts.
2. Handle session timeouts after a specified duration.
3. Validate existing sessions.
4. Store session data securely.
3. Class API:
- login(user_id: str) -> str: Logs in a user and returns the session ID.
- logout(session_id: str) -> None: Logs out a user by invalidating their session ID.
- is_valid_session(session_id: str) -> bool: Checks if the session ID is valid.
- get_session_data(session_id: str) -> dict: Retrieves the session data associated with a session ID.
4. Example 1:
- Input: login('user123') → Output: session_id_abc
- Explanation: User user123 successfully logs in and receives a session ID.
5. Constraints:
- Max 1000 active sessions.
- Session timeout duration: 30 minutes.
- Session IDs are unique.
- Thread-safe operations.

Start practicing xAI questions

Sign up for free to access walkthroughs, AI-generated questions, and more.

Get Started Free