Loading
Loading
A tutor wants to form study circles. Two students who know each other belong to the same circle, and so does anyone linked through a chain of acquaintances: if Asha knows Ben and Ben knows Chen, all three share a circle even if Asha and Chen have never met.
knows is an n × n grid where knows[i][j] = 1 when students i and j know each other. It is symmetric and every student knows themselves. Return the number of study circles.
knows = [[1,1,0,0,0],[1,1,1,0,0],[0,1,1,0,0],[0,0,0,1,1],[0,0,0,1,1]]5 circlesevery student starts alonemerge 0–14 circlesmerge 1–23 circlesmerge 3–42 circles: {0,1,2} and {3,4}2Sign in to keep a note here. It is free, and nobody else can see it.
Sign inExample 1
| 0 | 1 | 1 | 0 | 0 | 0 |
|---|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 0 | 0 |
| 2 | 0 | 1 | 1 | 0 | 0 |
| 3 | 0 | 0 |
Sign in to open hints.
Struggling is where the learning happens. Open this once you have genuinely tried, or once the hints have run out.
O(n²) time · O(n) space
Input. Run your code to watch it work on this input, one line at a time.
| 0 | 1 | 1 | 0 | 0 | 0 |
|---|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 0 | 0 |
| 2 | 0 | 1 | 1 | 0 | 0 |
| 3 | 0 | 0 | 0 | 1 | 1 |
| 4 | 0 | 0 | 0 | 1 | 1 |
Running code is turned off on this deployment. You can still read the problem, write code, use hints and the visualizer.
Tab moves focus out of the editor. Press Ctrl+M to let Tab indent instead.
No results yet
Run your code against the sample tests, or submit to run the full suite.
| 0 |
| 1 |
| 1 |
| 4 | 0 | 0 | 0 | 1 | 1 |
|---|
Example 2
| 0 | 1 | 0 | 0 | 0 |
|---|---|---|---|---|
| 1 | 0 | 1 | 0 | 0 |
| 2 | 0 | 0 | 1 | 0 |
| 3 | 0 | 0 | 0 | 1 |
Nobody knows anybody else, so every student is a circle of one.
Example 3
| 0 | 1 | 0 | 0 | 1 |
|---|---|---|---|---|
| 1 | 0 | 1 | 1 | 1 |
| 2 | 0 | 1 | 1 | 0 |
| 3 | 1 | 1 | 0 | 1 |