You are given a 2D integer array properties having dimensions n x m and an integer k.

Define a function intersect(a, b) that returns the number of distinct integers common to both arrays a and b.

Construct an undirected graph where each index i corresponds to properties[i]. There is an edge between node i and node j if and only if intersect(properties[i], properties[j]) >= k, where i and j are in the range [0, n - 1] and i != j.

Return the number of connected components in the resulting graph.

Input & Output

Example 1 — Basic Graph Formation
$ Input: properties = [[1,2,3],[1,3],[2,3,4]], k = 2
Output: 1
💡 Note: Intersections: properties[0] ∩ properties[1] = {1,3} (size 2 ≥ k), properties[0] ∩ properties[2] = {2,3} (size 2 ≥ k), properties[1] ∩ properties[2] = {3} (size 1 < k). Edges: 0-1, 0-2. Since node 0 connects to both nodes 1 and 2, all three nodes form one connected component.
Example 2 — No Connections
$ Input: properties = [[1,2],[3,4],[5,6]], k = 2
Output: 3
💡 Note: No two arrays have 2 or more common elements, so no edges exist. Each node forms its own component: 3 components total.
Example 3 — All Connected
$ Input: properties = [[1,2,3,4],[1,2,5,6],[2,3,7,8]], k = 2
Output: 1
💡 Note: All pairs have at least 2 common elements: (0,1) share {1,2}, (0,2) share {2,3}, (1,2) share {2}. Wait, (1,2) only share {2}, which is size 1 < k=2. So edges are 0-1 and 0-2, making one component {0,1,2}.

Constraints

  • 1 ≤ properties.length ≤ 103
  • 1 ≤ properties[i].length ≤ 103
  • 1 ≤ properties[i][j] ≤ 105
  • 1 ≤ k ≤ 103

Visualization

Tap to expand
Properties Graph - Connected Components INPUT properties array (n=3, m=3) 0 [1, 2, 3] 1 [1, 3] 2 [2, 3, 4] k = 2 Initial Graph Nodes: 0 {1,2,3} 1 {1,3} 2 {2,3,4} Input Values: properties = [[1,2,3], [1,3], [2,3,4]] k = 2 ALGORITHM STEPS 1 Convert to Hash Sets Each row becomes a set 2 Calculate Intersections For each pair (i,j) Intersection Counts: 0 ∩ 1: {1,3} = 2 >=k 0 ∩ 2: {2,3} = 2 >=k 1 ∩ 2: {3} = 1 <k 3 Build Graph Edges Add edge if count >= k 0 2 1 X 4 Count Components Use DFS/BFS/Union-Find FINAL RESULT Final Graph Structure: Component 1 0 2 Component 2 1 (isolated) Nodes 0 and 2 are connected Node 1 has no valid edges Output: 2 OK - 2 Connected Components Found Key Insight: Using Hash Sets for each row enables O(min(m1,m2)) intersection calculation instead of O(m1*m2). The graph has an edge between nodes i and j only when their property sets share at least k elements. Connected components can be found using DFS, BFS, or Union-Find in O(n^2) time complexity. TutorialsPoint - Properties Graph | Optimized with Hash Sets
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
12.0K Views
Medium Frequency
~25 min Avg. Time
245 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