fork download
  1. /*
  2. PROBLEM:
  3. Periodic-Color Binary Forest Roots
  4.  
  5. Given an undirected forest where every node has
  6. a color R, W, or B, find exactly one valid root
  7. for every connected component.
  8.  
  9. A valid rooted binary tree must satisfy:
  10.  
  11. 1. Every node has at most two children.
  12. 2. Parent-child colors follow the repeating cycle:
  13.   R -> W -> B -> R
  14. 3. The root can have any of the three colors.
  15. 4. Every component must have exactly one valid root.
  16.  
  17. Return the roots in increasing order.
  18.  
  19. If any component is invalid, return [].
  20.  
  21.  
  22. APPROACH: Edge Orientation + BFS Without Sorting
  23.  
  24. The color cycle uniquely determines the direction
  25. of every edge connecting two different colors.
  26.  
  27. Valid directions:
  28.  
  29.   R -> W
  30.   W -> B
  31.   B -> R
  32.  
  33. If two adjacent nodes have the same color,
  34. neither direction is valid.
  35.  
  36. Using these directions, we calculate the indegree
  37. of every node.
  38.  
  39.  
  40. INDEGREE AND OUTDEGREE:
  41.  
  42. indegree[node] = Number of parents
  43.  
  44. outdegree[node] = Number of children
  45.  
  46. Since every neighbor must be either a parent
  47. or a child:
  48.  
  49.   outdegree = degree - indegree
  50.  
  51. For a valid rooted binary tree:
  52.  
  53. - Root must have indegree 0.
  54. - Non-root nodes must have indegree 1.
  55. - Every node must have outdegree <= 2.
  56.  
  57.  
  58. ALGORITHM:
  59.  
  60. 1. Construct an undirected adjacency list.
  61.  
  62. 2. Process every edge:
  63.   a. Reject identical endpoint colors.
  64.   b. Determine the valid edge direction.
  65.   c. Increment the child's indegree.
  66.  
  67. 3. Use BFS to traverse every connected component.
  68.  
  69. 4. During BFS:
  70.   a. If indegree == 0, collect the root candidate.
  71.   b. If indegree > 1, return [].
  72.   c. Calculate children = degree - indegree.
  73.   d. If children > 2, return [].
  74.  
  75. 5. After processing each component:
  76.   a. Ensure exactly one root candidate exists.
  77.   b. Mark that node in the isRoot boolean array.
  78.  
  79. 6. Iterate through nodes from 0 to n - 1.
  80.   Collect every node marked as a root.
  81.  
  82. 7. Return the roots.
  83.  
  84.  
  85. WHY IS SORTING UNNECESSARY?
  86.  
  87. In the previous BFS solution, roots were collected
  88. in the order in which components were discovered.
  89.  
  90. For example:
  91.  
  92.   roots = [3, 2]
  93.  
  94. We then had to sort them.
  95.  
  96. Instead, we mark the roots in a boolean array:
  97.  
  98.   isRoot = [false, false, true, true]
  99.  
  100. When we iterate through this array from index
  101. 0 to n - 1, we automatically collect:
  102.  
  103.   roots = [2, 3]
  104.  
  105. This eliminates the sorting operation.
  106.  
  107.  
  108. WHY DOES THIS WORK?
  109.  
  110. The color cycle uniquely determines all
  111. parent-child relationships.
  112.  
  113. BFS validates that every connected component has:
  114.  
  115. - Exactly one node with indegree 0.
  116. - Every other node with indegree 1.
  117. - Every node with at most two children.
  118.  
  119. Since the input is guaranteed to be a forest,
  120. these conditions ensure that every component
  121. forms a valid rooted binary tree.
  122.  
  123. The final linear scan returns the roots
  124. in increasing order.
  125.  
  126.  
  127. TIME COMPLEXITY: O(V + E) = O(V)
  128.  
  129. V = Number of nodes
  130. E = Number of edges
  131. C = Number of connected components
  132.  
  133. - Construct adjacency list: O(V + E)
  134. - Calculate indegrees: O(E)
  135. - Initialize seen and isRoot arrays: O(V)
  136. - BFS across all components: O(V + E)
  137. - Mark roots: O(C)
  138. - Collect roots in increasing order: O(V)
  139.  
  140. Total:
  141.  
  142.   O(V + E + C)
  143.  
  144. Since C <= V:
  145.  
  146.   O(V + E)
  147.  
  148. Since the input is a forest:
  149.  
  150.   E = V - C
  151.   E < V
  152.  
  153. Therefore, total time complexity is O(V).
  154.  
  155. No sorting is required.
  156.  
  157.  
  158. SPACE COMPLEXITY: O(V + E) = O(V)
  159.  
  160. - Adjacency list: O(V + E)
  161. - Indegree array: O(V)
  162. - Seen array: O(V)
  163. - isRoot array: O(V)
  164. - BFS queue: O(V)
  165. - Root candidates: O(V)
  166. - Result array: O(C)
  167.  
  168. Total: O(V + E)
  169.  
  170. Since E < V, space complexity is O(V).
  171. */
  172.  
  173.  
  174. // ==================== SOLUTION ====================
  175.  
  176. function findPeriodicColorForestRoots(n, edges, colors) {
  177.  
  178. // Initialize the undirected adjacency list.
  179. const graph = Array.from({ length: n }, () => []);
  180.  
  181. // indegree[node] represents the number of parents.
  182. const indegree = Array(n).fill(0);
  183.  
  184. // Numerical representation of the color cycle:
  185. // R -> W -> B -> R
  186. // 0 -> 1 -> 2 -> 0
  187. const order = {
  188. R: 0,
  189. W: 1,
  190. B: 2
  191. };
  192.  
  193.  
  194. // STEP 1: Construct graph and calculate indegrees.
  195.  
  196. for (const [u, v] of edges) {
  197.  
  198. // Store the edge in both directions because
  199. // BFS traverses the original undirected graph.
  200. graph[u].push(v);
  201. graph[v].push(u);
  202.  
  203. // Adjacent nodes cannot have identical colors.
  204. if (colors[u] === colors[v]) {
  205. return [];
  206. }
  207.  
  208. // Check whether v's color follows u's color.
  209. if ((order[colors[u]] + 1) % 3 === order[colors[v]]) {
  210.  
  211. // Valid direction: u -> v
  212. // u is the parent of v.
  213. indegree[v]++;
  214.  
  215. } else {
  216.  
  217. // Valid direction: v -> u
  218. // v is the parent of u.
  219. indegree[u]++;
  220. }
  221. }
  222.  
  223.  
  224. // Tracks nodes already discovered by BFS.
  225. const seen = Array(n).fill(false);
  226.  
  227. // Marks the unique valid root of each component.
  228. //
  229. // Instead of collecting roots directly and sorting
  230. // them later, we mark them in this boolean array.
  231. const isRoot = Array(n).fill(false);
  232.  
  233.  
  234. // STEP 2: Traverse every connected component.
  235.  
  236. for (let start = 0; start < n; start++) {
  237.  
  238. // Skip nodes belonging to processed components.
  239. if (seen[start]) continue;
  240.  
  241. // Initialize BFS for a new connected component.
  242. const q = [start];
  243. let head = 0;
  244.  
  245. // Mark as seen when enqueuing.
  246. seen[start] = true;
  247.  
  248. // Stores root candidates for this component.
  249. const candidates = [];
  250.  
  251.  
  252. // BFS traversal.
  253. while (head < q.length) {
  254.  
  255. const node = q[head++];
  256.  
  257.  
  258. // CONDITION 1: Validate number of parents.
  259.  
  260. if (indegree[node] === 0) {
  261.  
  262. // A node without a parent is a
  263. // potential root.
  264. candidates.push(node);
  265.  
  266. } else if (indegree[node] > 1) {
  267.  
  268. // A node cannot have multiple parents.
  269. //
  270. // Return from the entire function
  271. // because any invalid component makes
  272. // the entire forest invalid.
  273. return [];
  274. }
  275.  
  276.  
  277. // CONDITION 2: Validate number of children.
  278.  
  279. // Total neighbors = parents + children
  280. //
  281. // Therefore:
  282. // children = degree - indegree
  283. const children =
  284. graph[node].length - indegree[node];
  285.  
  286. // A binary tree allows at most two children.
  287. if (children > 2) {
  288. return [];
  289. }
  290.  
  291.  
  292. // Visit all unvisited neighbors.
  293. for (const next of graph[node]) {
  294.  
  295. if (!seen[next]) {
  296.  
  297. // Mark before enqueuing to avoid
  298. // duplicate entries.
  299. seen[next] = true;
  300.  
  301. q.push(next);
  302. }
  303. }
  304. }
  305.  
  306.  
  307. // CONDITION 3: Validate unique root.
  308.  
  309. // Every component must have exactly one root.
  310. if (candidates.length !== 1) {
  311. return [];
  312. }
  313.  
  314.  
  315. // OPTIMIZATION:
  316. //
  317. // Instead of:
  318. // roots.push(candidates[0]);
  319. //
  320. // Mark the root in the boolean array.
  321. isRoot[candidates[0]] = true;
  322. }
  323.  
  324.  
  325. // STEP 3: Collect roots in increasing order.
  326.  
  327. const roots = [];
  328.  
  329. // Iterate through node IDs in increasing order.
  330. for (let node = 0; node < n; node++) {
  331.  
  332. // Collect every node marked as a valid root.
  333. if (isRoot[node]) {
  334. roots.push(node);
  335. }
  336. }
  337.  
  338.  
  339. // STEP 4: Return the result.
  340. //
  341. // Roots are already sorted.
  342. // No sorting operation is required.
  343. return roots;
  344. }
  345.  
  346.  
  347. // ==================== TEST CASES ====================
  348.  
  349. const tests = [
  350.  
  351. {
  352. name: "Normal valid binary tree",
  353. n: 4,
  354. edges: [[0, 1], [1, 2], [1, 3]],
  355. colors: "RWBB",
  356. expected: [0]
  357. },
  358.  
  359. {
  360. name: "Multiple valid connected components",
  361. n: 6,
  362. edges: [[0, 1], [1, 2], [3, 4], [4, 5]],
  363. colors: "RWBRWB",
  364. expected: [0, 3]
  365. },
  366.  
  367. {
  368. name: "Adjacent nodes have identical colors",
  369. n: 3,
  370. edges: [[0, 1], [1, 2]],
  371. colors: "RRB",
  372. expected: []
  373. },
  374.  
  375. {
  376. name: "Node has multiple parents",
  377. n: 3,
  378. edges: [[0, 1], [1, 2]],
  379. colors: "RWR",
  380. expected: []
  381. },
  382.  
  383. {
  384. name: "Root has three children",
  385. n: 4,
  386. edges: [[0, 1], [0, 2], [0, 3]],
  387. colors: "RWWW",
  388. expected: []
  389. },
  390.  
  391. {
  392. name: "White-colored root",
  393. n: 3,
  394. edges: [[0, 1], [1, 2]],
  395. colors: "WBR",
  396. expected: [0]
  397. },
  398.  
  399. {
  400. name: "Blue-colored root",
  401. n: 3,
  402. edges: [[0, 1], [1, 2]],
  403. colors: "BRW",
  404. expected: [0]
  405. },
  406.  
  407. {
  408. name: "Root is not the BFS starting node",
  409. n: 3,
  410. edges: [[0, 1], [1, 2]],
  411. colors: "BWR",
  412. expected: [2]
  413. },
  414.  
  415. {
  416. name: "Single isolated node",
  417. n: 1,
  418. edges: [],
  419. colors: "B",
  420. expected: [0]
  421. },
  422.  
  423. {
  424. name: "Multiple isolated nodes",
  425. n: 4,
  426. edges: [],
  427. colors: "RWBR",
  428. expected: [0, 1, 2, 3]
  429. },
  430.  
  431. {
  432. name: "Valid component followed by invalid component",
  433. n: 5,
  434. edges: [[0, 1], [2, 3], [3, 4]],
  435. colors: "RWRWR",
  436. expected: []
  437. },
  438.  
  439. {
  440. name: "Roots discovered in reverse order",
  441. n: 4,
  442. edges: [[0, 3], [1, 2]],
  443. colors: "WWRR",
  444. expected: [2, 3]
  445. },
  446.  
  447. {
  448. name: "Unsorted edges and reversed endpoints",
  449. n: 4,
  450. edges: [[3, 1], [2, 1], [1, 0]],
  451. colors: "RWBB",
  452. expected: [0]
  453. },
  454.  
  455. {
  456. name: "Repeating color cycle across multiple depths",
  457. n: 7,
  458. edges: [
  459. [0, 1],
  460. [1, 2],
  461. [2, 3],
  462. [3, 4],
  463. [4, 5],
  464. [5, 6]
  465. ],
  466. colors: "RWBRWBR",
  467. expected: [0]
  468. },
  469.  
  470. {
  471. name: "Connected component with isolated nodes",
  472. n: 5,
  473. edges: [[0, 1], [1, 2]],
  474. colors: "RWBRW",
  475. expected: [0, 3, 4]
  476. },
  477.  
  478. {
  479. name: "Root has exactly two children",
  480. n: 3,
  481. edges: [[0, 1], [0, 2]],
  482. colors: "RWW",
  483. expected: [0]
  484. }
  485. ];
  486.  
  487.  
  488. // ==================== TEST RUNNER ====================
  489.  
  490. let passed = 0;
  491.  
  492. tests.forEach((test, index) => {
  493.  
  494. const actual = findPeriodicColorForestRoots(
  495. test.n,
  496. test.edges,
  497. test.colors
  498. );
  499.  
  500. const isCorrect =
  501. JSON.stringify(actual) ===
  502. JSON.stringify(test.expected);
  503.  
  504. if (isCorrect) passed++;
  505.  
  506. console.log(`Test ${index + 1}: ${test.name}`);
  507. console.log("Expected:", JSON.stringify(test.expected));
  508. console.log("Actual: ", JSON.stringify(actual));
  509. console.log("Result: ", isCorrect ? "PASS" : "FAIL");
  510. console.log("----------------------------------------");
  511. });
  512.  
  513. console.log(`Total passed: ${passed}/${tests.length}`);
Success #stdin #stdout 0.03s 5712KB
stdin
Standard input is empty
stdout
Test 1: Normal valid binary tree
Expected: [0]
Actual:   [0]
Result:   PASS
----------------------------------------
Test 2: Multiple valid connected components
Expected: [0,3]
Actual:   [0,3]
Result:   PASS
----------------------------------------
Test 3: Adjacent nodes have identical colors
Expected: []
Actual:   []
Result:   PASS
----------------------------------------
Test 4: Node has multiple parents
Expected: []
Actual:   []
Result:   PASS
----------------------------------------
Test 5: Root has three children
Expected: []
Actual:   []
Result:   PASS
----------------------------------------
Test 6: White-colored root
Expected: [0]
Actual:   [0]
Result:   PASS
----------------------------------------
Test 7: Blue-colored root
Expected: [0]
Actual:   [0]
Result:   PASS
----------------------------------------
Test 8: Root is not the BFS starting node
Expected: [2]
Actual:   [2]
Result:   PASS
----------------------------------------
Test 9: Single isolated node
Expected: [0]
Actual:   [0]
Result:   PASS
----------------------------------------
Test 10: Multiple isolated nodes
Expected: [0,1,2,3]
Actual:   [0,1,2,3]
Result:   PASS
----------------------------------------
Test 11: Valid component followed by invalid component
Expected: []
Actual:   []
Result:   PASS
----------------------------------------
Test 12: Roots discovered in reverse order
Expected: [2,3]
Actual:   [2,3]
Result:   PASS
----------------------------------------
Test 13: Unsorted edges and reversed endpoints
Expected: [0]
Actual:   [0]
Result:   PASS
----------------------------------------
Test 14: Repeating color cycle across multiple depths
Expected: [0]
Actual:   [0]
Result:   PASS
----------------------------------------
Test 15: Connected component with isolated nodes
Expected: [0,3,4]
Actual:   [0,3,4]
Result:   PASS
----------------------------------------
Test 16: Root has exactly two children
Expected: [0]
Actual:   [0]
Result:   PASS
----------------------------------------
Total passed: 16/16