bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Data Interview Question

Friendship Status Check

bugfree Icon

Hello, I am bugfree Assistant. Feel free to ask me for any question related to this problem

Answer

To determine if two specified users are currently friends on Meta/Facebook, given the data on their interactions, we can use a combination of SQL queries and data processing techniques. Below are the steps and a SQL-based solution to solve the problem:

Step-by-Step Solution:

  1. Data Structure Setup:

    • Assume we have a table named fb_relationships to track the friendship status between users.

    • The table structure is as follows:

      CREATE TABLE fb_relationships (
          id BIGINT PRIMARY KEY,
          user1 BIGINT,
          user2 BIGINT,
          status BIT,  -- 1 for active friendship, 0 for inactive
          last_modified TIMESTAMP
      );
      
  2. Recording Historical Data:

    • To maintain a history of friending and unfriending activities, we can use a NoSQL database or a separate table to track each action.

    • Example structure for historical records:

      {
          "id": 1,
          "user1": "userA",
          "user2": "userB",
          "timestamp": "2021-01-01T13:45:00",
          "action": "friend"
      }
      
  3. SQL Query to Determine Current Friendship Status:

    • To check if two users are currently friends, execute the following SQL query:

      SELECT *
      FROM fb_relationships
      WHERE (user1 = :userA AND user2 = :userB OR
             user1 = :userB AND user2 = :userA)
        AND status = 1
        AND last_modified = (
            SELECT MAX(last_modified)
            FROM fb_relationships
            WHERE (user1 = :userA AND user2 = :userB OR
                   user1 = :userB AND user2 = :userA)
        );
      
    • This query checks if there is an active friendship status (status = 1) for the latest record between the specified users.

  4. Interpreting the Results:

    • If the query returns a result, then the users are currently friends.
    • If the query returns no result, then the users are not currently friends.
  5. Considerations for Scalability and Optimization:

    • Ensure indexes are created on user1, user2, and last_modified columns for faster query execution.
    • Consider using a caching mechanism if frequent checks are needed for the same user pairs.
  6. Handling Edge Cases:

    • Ensure data integrity by validating inputs to avoid SQL injection.
    • Handle cases where users have never interacted or have only unfriended each other.

By following these steps, we can efficiently determine the current friendship status between any two specified users using a combination of SQL queries and database design principles.