← Openai Interview Insights

Openai·Software Engineer·Onsite - Coding / Algorithms·Senior

Senior
Jun 2026

Summary

Two pretty dense coding problems for an OpenAI SWE loop, one graph simulation and one snapshot data structure. The problems kept growing with follow-ups so it felt less like two questions and more like six.

Questions Asked (7)

Q1

Given a contact graph of n people and an initial set of infected individuals, find the minimum number of days until everyone is infected, or return -1 if some people can never be infected.

Algorithms & Data Structures
Author's notes

BFS from all initially infected nodes at once, basically a multi-source BFS.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Model the problem as a multi-source BFS on the contact graph, where the initial infected set are sources at day 0. Compute the shortest path from any source to each node; the answer is the maximum distance, or -1 if any node is unreachable.

Pro tip: Clarify edge cases upfront: empty graph, no initial infected, and disconnected components. Also mention that if the graph is large, BFS is optimal O(V+E) and can be parallelized or optimized with bitsets if needed.

1. Clarify the problem

Confirm that infection spreads to all neighbors each day, and that we need the minimum days until all are infected. Ask about graph representation (adjacency list/matrix) and constraints.

2. Model as multi-source BFS

Initialize a queue with all initially infected nodes at distance 0. Perform BFS, tracking the distance (day) each node gets infected.

3. Compute maximum distance

After BFS, if any node remains unvisited, return -1. Otherwise, the answer is the maximum distance assigned to any node.

4. Analyze complexity and edge cases

State time complexity O(V+E) and space O(V). Discuss edge cases: no initial infected (return -1 unless n=0), graph with isolated nodes, and all nodes initially infected (return 0).

Key Points to Mention

  • Multi-source BFS efficiently computes shortest paths from a set of sources.
  • Infection time equals the shortest path distance from the nearest initially infected node.
  • If the graph is disconnected and some component has no initial infected, return -1.
  • Time complexity O(V+E) and space O(V) for adjacency list representation.
  • Edge cases: n=0, no initial infected, all initially infected.
  • Alternative approaches like Dijkstra are unnecessary since edges are unweighted.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q2

Extend the disease spread model so that some people are initially immune. Immune people can't be infected and don't transmit. Return the number of days until no new infection can occur, and be ready to report which susceptible people were never infected.

Algorithms & Data Structures
Author's notes

Straightforward extension of the BFS, just skip immune nodes.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Model the spread as a BFS over days, where each day newly infected people are those susceptible with at least one infected neighbor. Track infected, immune, and susceptible sets, and stop when no new infections occur; the day count is the number of BFS layers. After termination, report susceptible nodes never infected.

Pro tip: Clarify that immune individuals are removed from the graph entirely for transmission purposes, and explicitly handle the edge case where patient zero is immune (then 0 days).

1. Clarify inputs and rules

Confirm the graph representation (adjacency list/matrix), initial infected set, and immune set. State that immune nodes cannot be infected or transmit.

2. Initialize data structures

Use a queue for BFS, a set for infected, a set for immune, and a set for susceptible (all nodes not initially infected or immune).

3. Simulate day-by-day spread

For each day, process all currently infected nodes, collect susceptible neighbors, and mark them as newly infected. Increment day count only if new infections occur.

4. Terminate and compute result

Stop when no new infections occur. Return the number of days (BFS layers). The remaining susceptible nodes are those never infected.

5. Analyze complexity and edge cases

Discuss time O(V+E) and space O(V). Handle edge cases: no initial infected, all immune, disconnected graph, and patient zero immune.

Key Points to Mention

  • BFS level-order traversal to simulate days
  • Immune nodes are excluded from infection and transmission
  • Tracking susceptible nodes to report never-infected
  • Time and space complexity O(V+E)
  • Edge cases: no initial infected, all immune, patient zero immune
  • Early termination when no new infections

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q3

Further extend the model so infected people recover and become immune after a fixed number of days. Return the first day when the system is stable, meaning no infected people remain and no future infections are possible.

Algorithms & Data StructuresTechnical Trade-offs
Author's notes

This is where it got genuinely tricky.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Model the system as a state machine where each person's status (susceptible, infected, immune) evolves daily. Simulate day by day, tracking the number of infected and the day each infected person will recover, until no infected remain and no new infections can occur (i.e., all infected have recovered and the susceptible population cannot be infected because there are no infected).

Pro tip: Clarify the infection model upfront (e.g., whether infection spreads to all susceptible or probabilistically) and discuss how you would handle large populations efficiently, perhaps using counts rather than individual tracking.

1. Clarify the model

Ask clarifying questions about the infection and recovery rules: How does infection spread? Is recovery exactly after a fixed number of days? Are there any births or deaths?

2. Define state and transitions

Define the state variables (e.g., number of susceptible, infected, immune) and the daily transition rules, including how infected become immune after the fixed recovery period.

3. Design simulation algorithm

Choose an efficient simulation approach: either track each individual's infection day or use a queue to schedule recoveries. Update counts each day.

4. Determine termination condition

The system is stable when there are no infected individuals and no new infections can occur. Since infection requires infected individuals, this means the day after the last infected recovers, provided no new infections occurred that day.

5. Return the first stable day

Simulate until the condition is met, then return the day number. Ensure you handle edge cases like initial population with no infected.

Key Points to Mention

  • Clarify the infection model: deterministic vs. probabilistic, and whether infection spreads to all susceptible or a subset.
  • Use a queue or array to track recovery days for infected individuals to efficiently update the number of infected.
  • The system is stable when infected count is zero and no new infections occur; this may happen the day after the last recovery if no new infections were generated that day.
  • Consider edge cases: initial state with no infected (stable on day 0), all susceptible infected immediately, or no recovery (infinite loop).
  • Discuss time and space complexity: O(N) time where N is the number of days until stability, and O(I) space for tracking infected, where I is the maximum number of infected at once.
  • If the population is large, consider using aggregate counts and mathematical modeling instead of individual simulation.

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q4

Add a Dead state to the disease model. Each person either recovers or dies after a fixed number of days. Dead people can't be infected or transmit. Return the day the system stabilizes and the final count of people in each state.

Algorithms & Data StructuresTechnical Trade-offs
Author's notes

By this point I was running low on time and mostly talked through it rather than coded it.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Model the system as a state machine with Susceptible, Infected, Recovered, and Dead states, using a day-by-day simulation. Track transitions based on fixed recovery/death durations, and stop when the state counts no longer change. Return the stabilization day and final counts.

Pro tip: Clarify whether the fixed number of days is from infection or from symptom onset, and whether deaths occur simultaneously with recoveries. This shows attention to detail and prevents off-by-one errors.

1. Define states and transitions

Identify the states (S, I, R, D) and the rules for moving between them, including the fixed duration for recovery or death.

2. Choose simulation approach

Decide between a day-by-day simulation or a more efficient event-driven approach, considering constraints like population size and time to stabilize.

3. Implement transition logic

For each day, update each infected individual based on their infection day: if days since infection equals the fixed duration, they either recover or die (with some probability).

4. Detect stabilization

Continue simulation until no new infections occur and all infected have transitioned, i.e., the counts of each state remain unchanged from one day to the next.

5. Return results

Output the day when stabilization occurs and the final counts of susceptible, infected, recovered, and dead individuals.

Key Points to Mention

  • State transition rules and fixed durations
  • Handling simultaneous transitions and potential conflicts
  • Efficiency considerations for large populations
  • Correctness of stabilization condition
  • Edge cases: zero infected initially, all die, etc.
  • Data structures for tracking infection days (e.g., queue)

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q5

Design and implement a FriendCircle class supporting follow, unfollow, snapshot, and getFriends operations where snapshots are immutable captures of the follow graph at a point in time.

System DesignAlgorithms & Data Structures
Author's notes

The snapshot part is what makes this interesting.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Start by clarifying requirements and constraints, then propose a design that separates the mutable follow graph from immutable snapshots. Use a versioned approach where each follow/unfollow operation creates a new version, and snapshots reference a specific version. Implement getFriends to query the appropriate version based on the snapshot.

Pro tip: Mention that snapshots can be implemented efficiently using persistent data structures or copy-on-write to avoid full copies, and discuss trade-offs between memory and performance. Also, consider concurrency and thread-safety if the system is multi-threaded.

1. Clarify Requirements

Ask about expected scale (number of users, operations per second), consistency requirements, and whether snapshots need to be persisted or can be in-memory. Clarify if follow relationships are directed (like Twitter) or undirected (like Facebook).

2. Design Data Model

Propose a data model: e.g., a map from user ID to a set of followee IDs for the current state, and a version number or timestamp. For snapshots, consider storing a reference to a persistent data structure or a copy of the graph at that version.

3. Implement Operations

For follow/unfollow, update the current graph and increment the version. For snapshot, capture the current version (or create a persistent copy). For getFriends, retrieve the friend list from the snapshot's version.

4. Optimize and Discuss Trade-offs

Discuss optimizations: using persistent data structures (e.g., immutable maps) to share structure between versions, or copy-on-write for snapshots. Compare with naive full copy. Mention time/space complexity for each operation.

5. Handle Edge Cases and Concurrency

Address edge cases: following/unfollowing non-existent users, self-follow, duplicate follows. If concurrent access is possible, discuss locking or lock-free approaches to ensure snapshot consistency.

Key Points to Mention

  • Versioning or timestamping to track graph state over time
  • Persistent data structures (e.g., immutable maps, balanced trees) for efficient snapshots
  • Copy-on-write or structural sharing to reduce memory overhead
  • Time and space complexity of each operation (follow, unfollow, snapshot, getFriends)
  • Concurrency control (e.g., read-write locks, MVCC) if applicable
  • Trade-offs between memory usage and snapshot isolation/performance

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q6

Add a recommendFriends operation to the FriendCircle class that, given a snapshot and a user, returns up to k recommended users ranked by number of mutual intermediate followers (two-hop candidates).

Algorithms & Data StructuresSystem Design
Author's notes

Classic friends-of-friends ranking.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Clarify the data model and constraints first, then propose an efficient algorithm that traverses the snapshot's friend graph to find two-hop candidates, counts mutual connections, and ranks them. Discuss trade-offs between precomputation and on-the-fly computation, and outline how to handle ties and scalability.

Pro tip: Mention that you would exclude the user themselves and existing direct friends from recommendations, and consider using a min-heap to efficiently select top k when the candidate set is large.

1. Clarify requirements and assumptions

Ask about the snapshot's data structure (e.g., adjacency list), whether the graph is directed or undirected, and what 'mutual intermediate followers' means precisely. Confirm that recommendations should exclude the user and their direct friends, and discuss tie-breaking rules.

2. Design the algorithm

Propose a two-hop traversal: for each direct friend of the user, iterate through their friends (excluding the user and direct friends) and count occurrences. Use a hash map to tally mutual connections, then sort or use a heap to get top k.

3. Analyze complexity and optimize

State time and space complexity (e.g., O(d * f) where d is degree, f is average friend count). Discuss optimizations like early termination, caching, or precomputing mutual friend counts if the operation is frequent.

4. Handle edge cases and scalability

Address cases like no candidates, fewer than k candidates, ties, and large graphs. Mention distributed processing or approximate algorithms if the graph is massive.

5. Test and validate

Outline test cases: small graphs, disconnected users, users with many friends, and performance tests. Suggest verifying correctness against a brute-force implementation.

Key Points to Mention

  • Graph representation: adjacency list vs. adjacency matrix and their trade-offs
  • Two-hop traversal to find candidates and count mutual connections
  • Use of hash map for counting and min-heap for top-k selection
  • Time and space complexity analysis (e.g., O(V + E) for traversal, O(k log k) for heap)
  • Exclusion of the user and direct friends from recommendations
  • Scalability considerations: caching, precomputation, or distributed graph processing

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.

Q7

Add a diffFriends operation that compares two snapshots for a given user and returns which users were added to and removed from their follow list between the two snapshots.

System DesignTechnical Trade-offsAPI & Integrations
Author's notes

Set difference, basically.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Clarify the data model and snapshot semantics, then design the diffFriends operation to compute set differences between the follow lists from two snapshots. Discuss API design, efficiency, and edge cases, and consider trade-offs between different implementations.

Pro tip: Demonstrate awareness of real-world constraints like large follow lists and snapshot storage by proposing an efficient algorithm and discussing how to handle scale. Mention that you would validate assumptions with the interviewer before diving into code.

1. Clarify requirements and assumptions

Ask questions to understand the snapshot format, whether snapshots are immutable, and how the follow list is represented (e.g., set, sorted list). Confirm the expected output format and any performance requirements.

2. Define the API and data structures

Propose a function signature, such as diffFriends(userId, snapshot1, snapshot2) returning added and removed lists. Choose appropriate data structures (e.g., hash sets) for efficient lookups.

3. Design the algorithm

Outline the steps: retrieve follow lists from both snapshots, compute set difference for added (snapshot2 - snapshot1) and removed (snapshot1 - snapshot2). Discuss time and space complexity.

4. Address edge cases and scalability

Consider cases like missing snapshots, empty follow lists, and large datasets. Discuss optimizations like streaming or parallel processing if needed.

5. Discuss trade-offs and alternatives

Compare approaches: in-memory vs. database-level diff, using sorted lists vs. hash sets, and trade-offs between precomputation and on-demand calculation.

Key Points to Mention

  • Snapshot representation and immutability
  • Efficient set difference algorithms (e.g., using hash sets)
  • API design: input parameters, return type, error handling
  • Time and space complexity analysis
  • Scalability considerations for large follow lists
  • Trade-offs between different implementation strategies

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.