Similar Problems

Similar Problems not available

Number Of Trusted Contacts Of A Customer - Leetcode Solution

Companies:

LeetCode:  Number Of Trusted Contacts Of A Customer Leetcode Solution

Difficulty: Medium

Topics: database  

Problem Statement:

Given a list of customer information including their id and trusted contacts, where id[i] is the customer's id and trusted_contacts[i] is a list of IDs representing the customer's trusted contacts.

Return the number of unique trusted contacts from all customers.

Example 1:

Input: customers = [[1,[2,3],[2,4],[3,4],[4,5]],[2,[1,3]]] Output: 3 Explanation: Customer 1 has trusted contacts [2,3,4,5], and customer 2 has trusted contacts [1,3]. The unique trusted contacts are [1,2,3].

Solution:

To solve this problem, we can traverse the given list of customers. For each customer, we will add their trusted contacts to a set. Once we have processed all the customers, we can return the size of the set which will give us the total number of unique trusted contacts.

Algorithm:

  1. Initialize a set named unique_contacts to keep track of the unique trusted contacts.
  2. Traverse the given list of customers.
  3. For each customer, add the trusted contacts to the unique_contacts set.
  4. Return the size of the unique_contacts set which represents the total number of unique trusted contacts.

Code:

Here is the Python code to solve this problem:

def num_trusted_contacts(customers): unique_contacts = set() for customer in customers: unique_contacts.update(customer[1:]) return len(unique_contacts)

Time Complexity:

The time complexity of this algorithm is O(N*K), where N is the number of customers and K is the average number of trusted contacts per customer. In the worst case, all customers may have the same set of trusted contacts which will result in the worst-case time complexity of O(N^2).

Space Complexity:

The space complexity of this algorithm is O(NK) as we are using a set to store the unique trusted contacts. In the worst case, all customers may have a unique set of trusted contacts which will result in the worst-case space complexity of O(NK).

Number Of Trusted Contacts Of A Customer Solution Code

1