Second Degree Follower - Problem

Given a social network Follow table with followee and follower columns, find all second-degree followers.

A second-degree follower is a user who:

  • Follows at least one user (appears as follower)
  • Is followed by at least one user (appears as followee)

Return the second-degree users and their follower count, ordered by follower alphabetically.

Table Schema

Follow
Column Name Type Description
followee PK varchar User being followed
follower PK varchar User who follows
Primary Key: (followee, follower)
Note: Each row represents a follow relationship. No self-following allowed.

Input & Output

Example 1 — Basic Second-Degree Followers
Input Table:
followee follower
A B
A C
B D
Output:
follower num
B 1
💡 Note:

User B follows A (appears as follower) and is followed by D (appears as followee). B is a second-degree follower with 1 follower (D). Users A and C only appear as followee/follower respectively, so they don't qualify.

Example 2 — Multiple Second-Degree Followers
Input Table:
followee follower
A B
B C
B D
D E
Output:
follower num
B 2
D 1
💡 Note:

User B follows A and is followed by C and D (2 followers). User D follows B and is followed by E (1 follower). Both are second-degree followers, ordered alphabetically.

Example 3 — No Second-Degree Followers
Input Table:
followee follower
A B
C D
Output:
follower num
💡 Note:

No user appears in both roles. B only follows, A and C are only followed, D only follows. No second-degree followers exist.

Constraints

  • followee != follower (no self-following)
  • 1 ≤ number of relationships ≤ 1000
  • All usernames are valid varchar strings

Visualization

Tap to expand
Second Degree Follower INPUT followee follower Alice Bob Bob Carol Carol Dave Alice Carol Bob Eve Social Graph: Alice Bob Carol Dave Eve ALGORITHM STEPS 1 Find Followees Users who follow someone followees: Bob, Carol 2 Find Followers Users who have followers followed: Alice, Bob, Carol 3 Intersect Sets Both follows AND is followed second_deg: Bob, Carol 4 Count Followers Group by, count, order by name SELECT followee, COUNT(*) GROUP BY followee ORDER BY followee FINAL RESULT followee count Bob 2 Carol 1 Why these users? Bob Follows: Carol Followed by: Carol, Eve Count = 2 [OK] Carol Follows: Dave Followed by: Bob Count = 1 [OK] Ordered alphabetically Key Insight: A second-degree follower exists in BOTH sets: as a followee (they follow someone) AND as someone who is followed. Use self-join or subqueries to find the intersection, then count followers per user. Time: O(n) | Space: O(n) where n is the number of follow relationships TutorialsPoint - Second Degree Follower | Optimal Solution
Asked in
Facebook 28 Twitter 22 LinkedIn 15
32.0K Views
Medium Frequency
~12 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen