FastPrepMinimum Friend API Calls

Minimum Friend API Calls

Mercor logoMercor● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

A friendship service exposes one operation: querying a user returns that user's direct friends. Each query counts as one API call.

You are given the complete undirected friendship pairs for an offline practice adapter, plus source and target. Return the minimum number of friend-list API calls along any chain from source to target. Return 0 when they are the same user and -1 when no chain exists.

Function

minimumFriendApiCalls(friendships: String[][], source: String, target: String) → int

Examples

Example 1

friendships = [["a","b"],["b","c"],["c","d"]]source = "a"target = "d"return = 3

The shortest chain has three friendship edges.

Example 2

friendships = [["alice","bob"]]source = "alice"target = "bob"return = 1

One query reaches the direct friend.

Example 3

friendships = [["a","b"],["c","d"]]source = "a"target = "d"return = -1

The users are in different connected components.

Constraints

  • 0 <= friendships.length <= 100000
  • Every pair contains two distinct nonempty user IDs of at most 40 characters.
  • source and target are nonempty user IDs.
  • Duplicate friendship pairs do not change the result.

More Mercor problems

See Mercor hiring insights
public int minimumFriendApiCalls(String[][] friendships, String source, String target) {
  // write your code here
}
friendships[["a","b"],["b","c"],["c","d"]]
source"a"
target"d"
expected3
Checking account…