#3493

Properties Graph

Medium
ArrayHash TableDepth-First SearchBreadth-First SearchUnion-FindGraph Theory
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(n)
O(n)
💡

Intuition

Time O(n²)Space O(n)

Using sets allows us to efficiently compute intersections. We can leverage DFS to find connected components in the graph formed by valid edges.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a graph using adjacency lists based on intersections.
  2. 2Step 2: Use DFS to explore each component, marking nodes as visited.
  3. 3Step 3: Count the number of times a new DFS starts, which indicates a new component.
solution.py21 lines
1def intersect(a, b): return len(set(a) & set(b))
2
3def countComponents(properties, k):
4    n = len(properties)
5    graph = [[] for _ in range(n)]
6    for i in range(n):
7        for j in range(i + 1, n):
8            if intersect(properties[i], properties[j]) >= k:
9                graph[i].append(j)
10                graph[j].append(i)
11    visited = [False] * n
12    def dfs(node):
13        visited[node] = True
14        for neighbor in graph[node]:
15            if not visited[neighbor]: dfs(neighbor)
16    components = 0
17    for i in range(n):
18        if not visited[i]:
19            dfs(i)
20            components += 1
21    return components

Complexity note: The intersection check is O(n) for each pair, leading to O(n²) in total. Space is used for the graph and visited array.

  • 1Using sets for intersections is efficient.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.