Properties Graph - Problem
Imagine you're a social network analyst tasked with finding communities based on shared interests! You have a collection of user profiles, where each profile contains a list of properties (interests, skills, hobbies, etc.).
Given a 2D integer array properties of dimensions n ร m and an integer k, your goal is to:
- Build an undirected graph where each user (row) is a node
- Connect two users with an edge if they share at least k common properties
- Count the number of connected components (separate communities)
The intersect(a, b) function returns the number of distinct integers common to both arrays. There's an edge between node i and node j if and only if intersect(properties[i], properties[j]) >= k.
Goal: Return the total number of connected components in the resulting graph.
Input & Output
example_1.py โ Basic Case
$
Input:
properties = [[1,2,3], [1,2], [2,3], [4,5]]
k = 2
โบ
Output:
2
๐ก Note:
Node 0 and 1 share [1,2] (2 elements >= k=2), so they're connected. Node 0 and 2 share [2,3] (2 elements >= k=2), so they're connected. This creates component {0,1,2}. Node 3 has properties [4,5] which don't intersect with others by โฅ2 elements, forming a separate component {3}. Total: 2 components.
example_2.py โ No Connections
$
Input:
properties = [[1], [2], [3]]
k = 2
โบ
Output:
3
๐ก Note:
No two nodes share 2 or more common properties (each has only 1 property, all different). Each node forms its own component: {0}, {1}, {2}. Total: 3 components.
example_3.py โ All Connected
$
Input:
properties = [[1,2,3,4], [1,2,5,6], [2,3,7,8]]
k = 2
โบ
Output:
1
๐ก Note:
Node 0 and 1 share [1,2] (2 elements >= k=2). Node 0 and 2 share [2,3] (2 elements >= k=2). Through transitivity, all nodes are in one connected component {0,1,2}. Total: 1 component.
Constraints
- 1 โค n โค 103
- 1 โค m โค 100
- 1 โค k โค m
- 1 โค properties[i][j] โค 104
- Each properties[i] contains distinct integers
Visualization
Tap to expand
Understanding the Visualization
1
User Profiles
Each user has a list of interests/properties
2
Find Common Interests
Compare each pair to find shared interests
3
Create Friendships
Connect users with k+ common interests
4
Count Communities
Count separate friend groups using Union-Find
Key Takeaway
๐ฏ Key Insight: Union-Find efficiently merges communities without building the full graph, using path compression and union by rank for optimal performance.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code