OpenAI questions

Follow Graph

OpenAIMedium

Build a small social network as the class SocialGraph. Users are identified by strings, compared as ordinary case-sensitive strings ("u10" < "u2"). Following is directed: follow("ann", "bob") means ann follows bob and says nothing about bob following ann. A user who has never been mentioned follows nobody.

Each test drives one SocialGraph() instance through a sequence of calls and checks every return value. Each example shows init (constructor arguments) and operations, a list of [method, [args]] calls; the output lists every call's return value.

Part 1: Follow and unfollow

Implement three methods:

  • follow(user, target) makes user follow target. Return True if the edge was added, False if user == target or the edge already exists.
  • unfollow(user, target) removes the edge user -> target. Return True if the edge existed, otherwise False.
  • followees(user) returns the list of users that user follows, sorted alphabetically.

Edges are directed: follow("ann", "bob") does not make bob follow ann.

  1. Example 1
    init
    []
    operations
    [["follow",["ann","bob"]],["follow",["ann","cy"]],["follow",["ann","bob"]],["follow",["ann","ann"]],["followees",["ann"]],["unfollow",["ann","bob"]],["unfollow",["ann","bob"]],["unfollow",["bob","ann"]],["followees",["ann"]],["followees",["bob"]],["followees",["zed"]],["follow",["bob","ann"]],["follow",["ann","bob"]],["followees",["ann"]],["followees",["bob"]]]
    Output
    [true,true,false,false,["bob","cy"],true,false,false,["cy"],[],[],true,true,["bob","cy"],["ann"]]

    Why: Following someone already followed, or following yourself, returns False and changes nothing. followees lists who a user follows in alphabetical order, and an unknown user follows nobody. Unfollowing a missing edge returns False, and edges are directed, so ann following bob says nothing about bob following ann.

Constraints

  • 1 <= len(operations) <= 10^3
  • 1 <= len(user) <= 10 for each name
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Follow Graph: OpenAI interview question | LoopCoach