fork download
  1. /*
  2. PROBLEM:
  3. Periodic-Color Binary Forest Roots
  4.  
  5. Given an undirected forest with n nodes, where every
  6. node has a color R, W, or B, find exactly one valid
  7. root 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 connected component must have exactly
  16.   one valid root.
  17.  
  18. Return the roots in increasing order.
  19.  
  20. If any connected component is invalid, return [].
  21.  
  22.  
  23. APPROACH: Indegree + Outdegree (Without BFS/DFS)
  24.  
  25. OBSERVATION 1: Unique edge orientation
  26.  
  27. The color cycle uniquely determines the direction
  28. of every edge connecting two different colors.
  29.  
  30. Valid parent-child relationships:
  31.  
  32.   R -> W
  33.   W -> B
  34.   B -> R
  35.  
  36. If two adjacent nodes have the same color,
  37. neither direction is valid.
  38.  
  39. Therefore, we can determine all parent-child
  40. relationships without knowing the root beforehand.
  41.  
  42.  
  43. OBSERVATION 2: Indegree and outdegree
  44.  
  45. indegree[node] = Number of parents
  46. outdegree[node] = Number of children
  47.  
  48. For a valid rooted binary tree:
  49.  
  50. - Root must have indegree 0.
  51. - Non-root nodes must have indegree 1.
  52. - Every node must have outdegree <= 2.
  53.  
  54. Therefore:
  55.  
  56. - indegree > 1 means multiple parents.
  57. - outdegree > 2 violates the binary tree condition.
  58.  
  59. Either condition makes the entire forest invalid.
  60.  
  61.  
  62. OBSERVATION 3: Why BFS/DFS is unnecessary
  63.  
  64. The input is guaranteed to be a forest.
  65.  
  66. Every connected component containing k nodes
  67. has exactly k - 1 edges.
  68.  
  69. Every directed edge contributes exactly one
  70. to the total indegree.
  71.  
  72. Therefore:
  73.  
  74.   Sum of indegrees = k - 1
  75.  
  76. We ensure that every node has indegree 0 or 1.
  77.  
  78. Let r be the number of nodes with indegree 0.
  79.  
  80. The remaining k - r nodes have indegree 1.
  81.  
  82. Therefore:
  83.  
  84.   k - r = k - 1
  85.   r = 1
  86.  
  87. Hence, every connected component automatically
  88. has exactly one node with indegree 0.
  89.  
  90. That node is the unique root.
  91.  
  92. Since the underlying graph is acyclic, following
  93. the parent of any non-root node must eventually
  94. lead to this unique root.
  95.  
  96. Therefore, we do not need to explicitly traverse
  97. or identify individual connected components.
  98.  
  99.  
  100. OBSERVATION 4: Why sorting is unnecessary
  101.  
  102. We iterate through the nodes from 0 to n - 1
  103. while collecting the roots.
  104.  
  105. Therefore, roots are automatically collected
  106. in increasing order.
  107.  
  108.  
  109. ALGORITHM:
  110.  
  111. 1. Initialize indegree and outdegree arrays.
  112.  
  113. 2. Process every edge:
  114.   a. Reject edges connecting identical colors.
  115.   b. Determine the valid direction using the
  116.   periodic color sequence.
  117.   c. Increment the parent's outdegree.
  118.   d. Increment the child's indegree.
  119.  
  120. 3. Iterate through every node:
  121.   a. If indegree > 1, return [].
  122.   b. If outdegree > 2, return [].
  123.   c. If indegree == 0, add the node to roots.
  124.  
  125. 4. Return roots.
  126.  
  127.  
  128. TIME COMPLEXITY: O(V + E) = O(V)
  129.  
  130. V = Number of nodes
  131. E = Number of edges
  132. C = Number of connected components
  133.  
  134. - Initialize indegree array: O(V)
  135. - Initialize outdegree array: O(V)
  136. - Process every edge: O(E)
  137. - Validate every node: O(V)
  138. - Collect roots: O(V), within the validation loop
  139.  
  140. Total:
  141.  
  142.   O(V) + O(V) + O(E) + O(V)
  143.   = O(V + E)
  144.  
  145. Since the input is a forest:
  146.  
  147.   E = V - C
  148.   E < V
  149.  
  150. Therefore, time complexity simplifies to O(V).
  151.  
  152. No BFS, DFS, or sorting is required.
  153.  
  154.  
  155. SPACE COMPLEXITY: O(V)
  156.  
  157. - Indegree array: O(V)
  158. - Outdegree array: O(V)
  159. - Roots array: O(C)
  160. - Color mapping: O(1)
  161.  
  162. Since C <= V:
  163.  
  164.   O(V + V + C) = O(V)
  165.  
  166. No adjacency list, visited array, BFS queue,
  167. or DFS stack is required.
  168.  
  169.  
  170. IMPORTANT ASSUMPTION:
  171.  
  172. The input must be a forest.
  173.  
  174. If cycles were allowed, a directed cycle could
  175. have indegree 1 and outdegree 1 for every node
  176. without having any root.
  177.  
  178. In that case, additional cycle detection would
  179. be necessary.
  180. */
  181.  
  182.  
  183. // ==================== SOLUTION ====================
  184.  
  185. function findPeriodicColorForestRoots(n, edges, colors) {
  186.  
  187. // Number of parents of each node.
  188. const indegree = Array(n).fill(0);
  189.  
  190. // Number of children of each node.
  191. const outdegree = Array(n).fill(0);
  192.  
  193. // Numerical representation of the color cycle:
  194. //
  195. // R -> W -> B -> R
  196. // 0 -> 1 -> 2 -> 0
  197. const order = {
  198. R: 0,
  199. W: 1,
  200. B: 2
  201. };
  202.  
  203.  
  204. // STEP 1: Determine the direction of every edge.
  205.  
  206. for (const [u, v] of edges) {
  207.  
  208. // Adjacent nodes cannot have the same color.
  209. //
  210. // For example:
  211. // R -> R is invalid in both directions.
  212. //
  213. // Therefore, no valid root selection exists.
  214. if (colors[u] === colors[v]) {
  215. return [];
  216. }
  217.  
  218.  
  219. // Check whether v's color is the next valid
  220. // color after u's color.
  221. //
  222. // For example:
  223. // R -> W: (0 + 1) % 3 === 1
  224. // W -> B: (1 + 1) % 3 === 2
  225. // B -> R: (2 + 1) % 3 === 0
  226. if ((order[colors[u]] + 1) % 3 === order[colors[v]]) {
  227.  
  228. // Valid direction: u -> v
  229. //
  230. // u is the parent of v.
  231. // v is the child of u.
  232.  
  233. // u gains one child.
  234. outdegree[u]++;
  235.  
  236. // v gains one parent.
  237. indegree[v]++;
  238.  
  239. } else {
  240.  
  241. // Valid direction: v -> u
  242. //
  243. // Since identical colors were already
  244. // rejected, exactly one of the two
  245. // directions must be valid.
  246. //
  247. // v is the parent of u.
  248. // u is the child of v.
  249.  
  250. // v gains one child.
  251. outdegree[v]++;
  252.  
  253. // u gains one parent.
  254. indegree[u]++;
  255. }
  256. }
  257.  
  258.  
  259. // Stores the unique root of each connected component.
  260. const roots = [];
  261.  
  262.  
  263. // STEP 2: Validate every node and collect roots.
  264.  
  265. for (let node = 0; node < n; node++) {
  266.  
  267. // CONDITION 1: Validate the number of parents.
  268. //
  269. // A valid rooted tree cannot have a node
  270. // with more than one parent.
  271. //
  272. // If any node has multiple parents, return []
  273. // from the entire function.
  274. if (indegree[node] > 1) {
  275. return [];
  276. }
  277.  
  278.  
  279. // CONDITION 2: Validate the number of children.
  280. //
  281. // A binary tree allows at most two children
  282. // per node, including the root.
  283. if (outdegree[node] > 2) {
  284. return [];
  285. }
  286.  
  287.  
  288. // CONDITION 3: Identify roots.
  289. //
  290. // A node with no parent must be a root.
  291. //
  292. // Because the input is a forest and every
  293. // node has at most one parent, each connected
  294. // component is guaranteed to have exactly
  295. // one zero-indegree node if all checks pass.
  296. if (indegree[node] === 0) {
  297. roots.push(node);
  298. }
  299. }
  300.  
  301.  
  302. // STEP 3: Return the roots.
  303. //
  304. // Since we iterate through nodes from 0 to n - 1,
  305. // the roots are already in increasing order.
  306. //
  307. // No sorting is required.
  308. return roots;
  309. }
  310.  
  311.  
  312. // ==================== TEST CASES ====================
  313.  
  314. const tests = [
  315.  
  316. {
  317. name: "Normal valid binary tree",
  318. n: 4,
  319. edges: [[0, 1], [1, 2], [1, 3]],
  320. colors: "RWBB",
  321. expected: [0]
  322. },
  323.  
  324. {
  325. name: "Multiple valid connected components",
  326. n: 6,
  327. edges: [[0, 1], [1, 2], [3, 4], [4, 5]],
  328. colors: "RWBRWB",
  329. expected: [0, 3]
  330. },
  331.  
  332. {
  333. name: "Adjacent nodes have identical colors",
  334. n: 3,
  335. edges: [[0, 1], [1, 2]],
  336. colors: "RRB",
  337. expected: []
  338. },
  339.  
  340. {
  341. name: "Node has multiple parents",
  342. n: 3,
  343. edges: [[0, 1], [1, 2]],
  344. colors: "RWR",
  345. expected: []
  346. },
  347.  
  348. {
  349. name: "Root has three children",
  350. n: 4,
  351. edges: [[0, 1], [0, 2], [0, 3]],
  352. colors: "RWWW",
  353. expected: []
  354. },
  355.  
  356. {
  357. name: "White-colored root",
  358. n: 3,
  359. edges: [[0, 1], [1, 2]],
  360. colors: "WBR",
  361. expected: [0]
  362. },
  363.  
  364. {
  365. name: "Blue-colored root",
  366. n: 3,
  367. edges: [[0, 1], [1, 2]],
  368. colors: "BRW",
  369. expected: [0]
  370. },
  371.  
  372. {
  373. name: "Root is not the smallest node",
  374. n: 3,
  375. edges: [[0, 1], [1, 2]],
  376. colors: "BWR",
  377. expected: [2]
  378. },
  379.  
  380. {
  381. name: "Single isolated node",
  382. n: 1,
  383. edges: [],
  384. colors: "B",
  385. expected: [0]
  386. },
  387.  
  388. {
  389. name: "Multiple isolated nodes",
  390. n: 4,
  391. edges: [],
  392. colors: "RWBR",
  393. expected: [0, 1, 2, 3]
  394. },
  395.  
  396. {
  397. name: "Valid component followed by invalid component",
  398. n: 5,
  399. edges: [[0, 1], [2, 3], [3, 4]],
  400. colors: "RWRWR",
  401. expected: []
  402. },
  403.  
  404. {
  405. name: "Roots automatically collected in sorted order",
  406. n: 4,
  407. edges: [[0, 3], [1, 2]],
  408. colors: "WWRR",
  409. expected: [2, 3]
  410. },
  411.  
  412. {
  413. name: "Unsorted edges and reversed endpoints",
  414. n: 4,
  415. edges: [[3, 1], [2, 1], [1, 0]],
  416. colors: "RWBB",
  417. expected: [0]
  418. },
  419.  
  420. {
  421. name: "Repeating color cycle across multiple depths",
  422. n: 7,
  423. edges: [
  424. [0, 1],
  425. [1, 2],
  426. [2, 3],
  427. [3, 4],
  428. [4, 5],
  429. [5, 6]
  430. ],
  431. colors: "RWBRWBR",
  432. expected: [0]
  433. },
  434.  
  435. {
  436. name: "Connected component with isolated nodes",
  437. n: 5,
  438. edges: [[0, 1], [1, 2]],
  439. colors: "RWBRW",
  440. expected: [0, 3, 4]
  441. },
  442.  
  443. {
  444. name: "Root has exactly two children",
  445. n: 3,
  446. edges: [[0, 1], [0, 2]],
  447. colors: "RWW",
  448. expected: [0]
  449. }
  450. ];
  451.  
  452.  
  453. // ==================== TEST RUNNER ====================
  454.  
  455. let passed = 0;
  456.  
  457. tests.forEach((test, index) => {
  458.  
  459. const actual = findPeriodicColorForestRoots(
  460. test.n,
  461. test.edges,
  462. test.colors
  463. );
  464.  
  465. // Compare actual and expected arrays.
  466. const isCorrect =
  467. JSON.stringify(actual) ===
  468. JSON.stringify(test.expected);
  469.  
  470. if (isCorrect) passed++;
  471.  
  472. console.log(`Test ${index + 1}: ${test.name}`);
  473. console.log("Expected:", JSON.stringify(test.expected));
  474. console.log("Actual: ", JSON.stringify(actual));
  475. console.log("Result: ", isCorrect ? "PASS" : "FAIL");
  476. console.log("----------------------------------------");
  477. });
  478.  
  479. console.log(`Total passed: ${passed}/${tests.length}`);
Success #stdin #stdout 0.03s 5624KB
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 smallest 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 automatically collected in sorted 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