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 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.  
  16. Return the roots in increasing order.
  17.  
  18. If any component does not have exactly one valid
  19. root, return an empty array.
  20.  
  21.  
  22. APPROACH: Edge Orientation + Indegree + BFS
  23.  
  24. Instead of trying every node as a potential root,
  25. we use the colors to determine the direction of
  26. every undirected edge.
  27.  
  28. The only valid parent-child relationships are:
  29.  
  30.   R -> W
  31.   W -> B
  32.   B -> R
  33.  
  34. For example, if an edge connects a red node and
  35. a white node, the red node must be the parent
  36. and the white node must be the child.
  37.  
  38. Therefore, every edge with different-colored
  39. endpoints has exactly one valid direction.
  40.  
  41.  
  42. ALGORITHM:
  43.  
  44. 1. Construct an undirected adjacency list.
  45.  
  46. 2. Calculate the indegree of every node by
  47.   determining the direction of every edge.
  48.  
  49.   If both endpoints have the same color,
  50.   immediately return [].
  51.  
  52. 3. Use BFS to traverse each connected component.
  53.  
  54. 4. During BFS, validate every node:
  55.  
  56.   a. indegree == 0:
  57.   The node has no parent and is a root candidate.
  58.  
  59.   b. indegree == 1:
  60.   The node has exactly one parent and is valid
  61.   as a non-root node.
  62.  
  63.   c. indegree > 1:
  64.   The node has multiple parents, which is invalid.
  65.   Return [] for the entire forest.
  66.  
  67.   d. Calculate the number of children:
  68.  
  69.   children = degree - indegree
  70.  
  71.   If children > 2, return [].
  72.  
  73. 5. After processing a connected component,
  74.   ensure that it has exactly one root candidate.
  75.  
  76. 6. Add that root to the answer.
  77.  
  78. 7. Sort the roots in increasing order and return.
  79.  
  80.  
  81. WHY DOES THIS WORK?
  82.  
  83. The color cycle uniquely determines the direction
  84. of every edge.
  85.  
  86. Once the edges are oriented, a valid rooted binary
  87. tree must have:
  88.  
  89. - Exactly one node with indegree 0.
  90. - Every other node with indegree 1.
  91. - Every node with outdegree at most 2.
  92.  
  93. Since the input is guaranteed to be a forest,
  94. there are no cycles.
  95.  
  96. Therefore, satisfying these conditions ensures
  97. that every component forms a valid rooted binary
  98. tree with the required periodic color sequence.
  99.  
  100.  
  101. TIME COMPLEXITY: O(V + E + C log C)
  102.  
  103. V = Number of nodes
  104. E = Number of edges
  105. C = Number of connected components
  106.  
  107. - Construct adjacency list: O(V + E)
  108. - Calculate indegrees: O(E)
  109. - Initialize arrays: O(V)
  110. - BFS across all components: O(V + E)
  111. - Sort the roots: O(C log C)
  112.  
  113. Total: O(V + E + C log C)
  114.  
  115. Since the input is a forest:
  116.   E < V
  117.   C <= V
  118.  
  119. Overall time complexity upper bound: O(V log V)
  120.  
  121.  
  122. SPACE COMPLEXITY: O(V + E)
  123.  
  124. - Adjacency list: O(V + E)
  125. - Indegree array: O(V)
  126. - Seen array: O(V)
  127. - BFS queue: O(V)
  128. - Root candidates: O(V)
  129. - Result array: O(C)
  130. - Sorting auxiliary space: O(C) worst case
  131.  
  132. Total: O(V + E)
  133.  
  134. Since E < V, space complexity simplifies to O(V).
  135. */
  136.  
  137.  
  138. // ==================== SOLUTION ====================
  139.  
  140. function findPeriodicColorForestRoots(n, edges, colors) {
  141.  
  142. // Step 1: Initialize adjacency list
  143. const graph = Array.from({ length: n }, () => []);
  144.  
  145. // indegree[node] represents the number of parents
  146. // of the node according to the color cycle.
  147. const indegree = Array(n).fill(0);
  148.  
  149. // Numerical representation of the color cycle:
  150. // R -> W -> B -> R
  151. // 0 -> 1 -> 2 -> 0
  152. const order = {
  153. R: 0,
  154. W: 1,
  155. B: 2
  156. };
  157.  
  158.  
  159. // Step 2: Construct graph and calculate indegrees
  160. for (const [u, v] of edges) {
  161.  
  162. // Store the edge in both directions because
  163. // the original graph is undirected.
  164. graph[u].push(v);
  165. graph[v].push(u);
  166.  
  167. // Two adjacent nodes cannot have the same color.
  168. // Neither orientation would be valid.
  169. if (colors[u] === colors[v]) {
  170. return [];
  171. }
  172.  
  173. // Check whether v's color is the next color
  174. // after u's color in the repeating cycle.
  175. if ((order[colors[u]] + 1) % 3 === order[colors[v]]) {
  176.  
  177. // Valid direction: u -> v
  178. // u is the parent of v.
  179. indegree[v]++;
  180.  
  181. } else {
  182.  
  183. // Valid direction: v -> u
  184. // v is the parent of u.
  185. indegree[u]++;
  186. }
  187. }
  188.  
  189.  
  190. // Tracks nodes already discovered by BFS.
  191. const seen = Array(n).fill(false);
  192.  
  193. // Stores the unique valid root of each component.
  194. const roots = [];
  195.  
  196.  
  197. // Step 3: Traverse every connected component
  198. for (let start = 0; start < n; start++) {
  199.  
  200. // This node belongs to an already processed
  201. // connected component.
  202. if (seen[start]) continue;
  203.  
  204. // Initialize BFS for a new component.
  205. const q = [start];
  206. let head = 0;
  207.  
  208. // Mark as seen when enqueuing to prevent
  209. // duplicate entries in the queue.
  210. seen[start] = true;
  211.  
  212. // Stores all root candidates in this component.
  213. const candidates = [];
  214.  
  215.  
  216. // BFS traversal
  217. while (head < q.length) {
  218.  
  219. const node = q[head++];
  220.  
  221.  
  222. // CONDITION 1: Validate number of parents
  223.  
  224. if (indegree[node] === 0) {
  225.  
  226. // A node with no parent is a potential root.
  227. candidates.push(node);
  228.  
  229. } else if (indegree[node] > 1) {
  230.  
  231. // A node cannot have multiple parents
  232. // in a rooted tree.
  233. //
  234. // Return from the entire function because
  235. // even one invalid component makes the
  236. // entire forest invalid.
  237. return [];
  238. }
  239.  
  240.  
  241. // CONDITION 2: Validate number of children
  242.  
  243. // Total neighbors = parents + children
  244. //
  245. // Therefore:
  246. // children = degree - indegree
  247. const children =
  248. graph[node].length - indegree[node];
  249.  
  250. // Every node must have at most two children.
  251. if (children > 2) {
  252. return [];
  253. }
  254.  
  255.  
  256. // Visit all unvisited neighbors.
  257. //
  258. // We traverse the original undirected graph
  259. // because BFS is only being used to identify
  260. // and validate connected components.
  261. for (const next of graph[node]) {
  262.  
  263. if (!seen[next]) {
  264. seen[next] = true;
  265. q.push(next);
  266. }
  267. }
  268. }
  269.  
  270.  
  271. // CONDITION 3: Validate unique root
  272.  
  273. // Every connected component must have exactly
  274. // one valid root candidate.
  275. if (candidates.length !== 1) {
  276. return [];
  277. }
  278.  
  279. // Store the unique root of this component.
  280. roots.push(candidates[0]);
  281. }
  282.  
  283.  
  284. // Step 4: Return roots in increasing order.
  285. return roots.sort((a, b) => a - b);
  286. }
  287.  
  288.  
  289. // ==================== TEST CASES ====================
  290.  
  291. const tests = [
  292.  
  293. {
  294. name: "Normal valid binary tree",
  295. n: 4,
  296. edges: [[0, 1], [1, 2], [1, 3]],
  297. colors: "RWBB",
  298. expected: [0]
  299. },
  300.  
  301. {
  302. name: "Multiple valid connected components",
  303. n: 6,
  304. edges: [[0, 1], [1, 2], [3, 4], [4, 5]],
  305. colors: "RWBRWB",
  306. expected: [0, 3]
  307. },
  308.  
  309. {
  310. name: "Adjacent nodes have the same color",
  311. n: 3,
  312. edges: [[0, 1], [1, 2]],
  313. colors: "RRB",
  314. expected: []
  315. },
  316.  
  317. {
  318. name: "Node has multiple parents",
  319. n: 3,
  320. edges: [[0, 1], [1, 2]],
  321. colors: "RWR",
  322. expected: []
  323. },
  324.  
  325. {
  326. name: "Root has three children",
  327. n: 4,
  328. edges: [[0, 1], [0, 2], [0, 3]],
  329. colors: "RWWW",
  330. expected: []
  331. },
  332.  
  333. {
  334. name: "Valid root is white",
  335. n: 3,
  336. edges: [[0, 1], [1, 2]],
  337. colors: "WBR",
  338. expected: [0]
  339. },
  340.  
  341. {
  342. name: "Valid root is blue",
  343. n: 3,
  344. edges: [[0, 1], [1, 2]],
  345. colors: "BRW",
  346. expected: [0]
  347. },
  348.  
  349. {
  350. name: "Root is not the BFS starting node",
  351. n: 3,
  352. edges: [[0, 1], [1, 2]],
  353. colors: "BWR",
  354. expected: [2]
  355. },
  356.  
  357. {
  358. name: "Single isolated node",
  359. n: 1,
  360. edges: [],
  361. colors: "B",
  362. expected: [0]
  363. },
  364.  
  365. {
  366. name: "Multiple isolated nodes",
  367. n: 4,
  368. edges: [],
  369. colors: "RWBR",
  370. expected: [0, 1, 2, 3]
  371. },
  372.  
  373. {
  374. name: "Valid component followed by invalid component",
  375. n: 5,
  376. edges: [[0, 1], [2, 3], [3, 4]],
  377. colors: "RWRWR",
  378. expected: []
  379. },
  380.  
  381. {
  382. name: "Roots must be sorted",
  383. n: 4,
  384. edges: [[0, 3], [1, 2]],
  385. colors: "WWRR",
  386. expected: [2, 3]
  387. },
  388.  
  389. {
  390. name: "Color cycle repeats across multiple depths",
  391. n: 7,
  392. edges: [
  393. [0, 1],
  394. [1, 2],
  395. [2, 3],
  396. [3, 4],
  397. [4, 5],
  398. [5, 6]
  399. ],
  400. colors: "RWBRWBR",
  401. expected: [0]
  402. }
  403. ];
  404.  
  405.  
  406. // ==================== TEST RUNNER ====================
  407.  
  408. let passed = 0;
  409.  
  410. tests.forEach((test, index) => {
  411.  
  412. const actual = findPeriodicColorForestRoots(
  413. test.n,
  414. test.edges,
  415. test.colors
  416. );
  417.  
  418. const isCorrect =
  419. JSON.stringify(actual) ===
  420. JSON.stringify(test.expected);
  421.  
  422. if (isCorrect) passed++;
  423.  
  424. console.log(`Test ${index + 1}: ${test.name}`);
  425. console.log("Expected:", JSON.stringify(test.expected));
  426. console.log("Actual: ", JSON.stringify(actual));
  427. console.log("Result: ", isCorrect ? "PASS" : "FAIL");
  428. console.log("----------------------------------------");
  429. });
  430.  
  431. console.log(`Total passed: ${passed}/${tests.length}`);
Success #stdin #stdout 0.03s 5636KB
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 the same color
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: Valid root is white
Expected: [0]
Actual:   [0]
Result:   PASS
----------------------------------------
Test 7: Valid root is blue
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 must be sorted
Expected: [2,3]
Actual:   [2,3]
Result:   PASS
----------------------------------------
Test 13: Color cycle repeats across multiple depths
Expected: [0]
Actual:   [0]
Result:   PASS
----------------------------------------
Total passed: 13/13