{"id":"6b093dddbd4755deb67ee058","slug":"build-order","title":"Kolejność budowania modułów","summary":"Monorepo ma moduły zależne od innych modułów. Wyznaczamy kolejność budowania albo wykrywamy cykl – sortowanie topologiczne algorytmem Kahna.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":[],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["graphs","topological-sort","bfs","cycle-detection","kahn"],"languages":[{"lang":"typescript","runner":"browser","starter":"/**\n * A build order of modules 0..n-1; [a, b] means \"a depends on b\" (b first).\n * Returns [] when the dependencies contain a cycle.\n */\nfunction buildOrder(n: number, dependencies: [number, number][]): number[] {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":7,"tests":"function assertValidOrder(n, dependencies, order) {\n  expect(order).toHaveLength(n);\n  const position = new Array(n).fill(-1);\n  order.forEach((m, i) => {\n    if (!Number.isInteger(m) || m < 0 || m >= n || position[m] !== -1) throw new Error('module ' + m + ' is invalid or repeated');\n    position[m] = i;\n  });\n  for (const [a, b] of dependencies) {\n    if (position[b] > position[a]) throw new Error(`module ${a} is built before its dependency ${b}`);\n  }\n}\n\ntest('a chain has exactly one order', () => {\n  expect(buildOrder(3, [[1, 0], [2, 1]])).toEqual([0, 1, 2]);\n});\n\ntest('a diamond', () => {\n  const deps = [[1, 0], [2, 0], [3, 1], [3, 2]];\n  assertValidOrder(4, deps, buildOrder(4, deps));\n});\n\ntest('modules without dependencies are included', () => {\n  assertValidOrder(3, [], buildOrder(3, []));\n  const deps = [[2, 0]];\n  assertValidOrder(5, deps, buildOrder(5, deps));\n});\n\ntest('cycles give an empty list', () => {\n  expect(buildOrder(2, [[0, 1], [1, 0]])).toEqual([]);\n  expect(buildOrder(3, [[0, 0]])).toEqual([]);\n  expect(buildOrder(4, [[1, 0], [2, 3], [3, 2]])).toEqual([]);\n  expect(buildOrder(3, [[0, 1], [1, 2], [2, 0]])).toEqual([]);\n});\n\ntest('repeated dependencies', () => {\n  const deps = [[1, 0], [1, 0], [2, 1], [2, 0], [2, 1]];\n  assertValidOrder(3, deps, buildOrder(3, deps));\n});\n\ntest('a single module', () => {\n  expect(buildOrder(1, [])).toEqual([0]);\n});\n\ntest('performance: 100 000 modules, 200 000 dependencies', () => {\n  const n = 100000;\n  const deps = [];\n  for (let i = 1; i < n; i++) {\n    deps.push([i, i - 1]);\n    deps.push([i, i >> 1]);\n  }\n  assertValidOrder(n, deps, buildOrder(n, deps));\n  deps.push([0, n - 1]);\n  expect(buildOrder(n, deps)).toEqual([]);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * A build order of modules 0..n-1; [a, b] means \"a depends on b\" (b first).\n * Returns [] when the dependencies contain a cycle.\n * @param {number} n\n * @param {number[][]} dependencies\n * @returns {number[]}\n */\nfunction buildOrder(n, dependencies) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":7,"tests":"function assertValidOrder(n, dependencies, order) {\n  expect(order).toHaveLength(n);\n  const position = new Array(n).fill(-1);\n  order.forEach((m, i) => {\n    if (!Number.isInteger(m) || m < 0 || m >= n || position[m] !== -1) throw new Error('module ' + m + ' is invalid or repeated');\n    position[m] = i;\n  });\n  for (const [a, b] of dependencies) {\n    if (position[b] > position[a]) throw new Error(`module ${a} is built before its dependency ${b}`);\n  }\n}\n\ntest('a chain has exactly one order', () => {\n  expect(buildOrder(3, [[1, 0], [2, 1]])).toEqual([0, 1, 2]);\n});\n\ntest('a diamond', () => {\n  const deps = [[1, 0], [2, 0], [3, 1], [3, 2]];\n  assertValidOrder(4, deps, buildOrder(4, deps));\n});\n\ntest('modules without dependencies are included', () => {\n  assertValidOrder(3, [], buildOrder(3, []));\n  const deps = [[2, 0]];\n  assertValidOrder(5, deps, buildOrder(5, deps));\n});\n\ntest('cycles give an empty list', () => {\n  expect(buildOrder(2, [[0, 1], [1, 0]])).toEqual([]);\n  expect(buildOrder(3, [[0, 0]])).toEqual([]);\n  expect(buildOrder(4, [[1, 0], [2, 3], [3, 2]])).toEqual([]);\n  expect(buildOrder(3, [[0, 1], [1, 2], [2, 0]])).toEqual([]);\n});\n\ntest('repeated dependencies', () => {\n  const deps = [[1, 0], [1, 0], [2, 1], [2, 0], [2, 1]];\n  assertValidOrder(3, deps, buildOrder(3, deps));\n});\n\ntest('a single module', () => {\n  expect(buildOrder(1, [])).toEqual([0]);\n});\n\ntest('performance: 100 000 modules, 200 000 dependencies', () => {\n  const n = 100000;\n  const deps = [];\n  for (let i = 1; i < n; i++) {\n    deps.push([i, i - 1]);\n    deps.push([i, i >> 1]);\n  }\n  assertValidOrder(n, deps, buildOrder(n, deps));\n  deps.push([0, n - 1]);\n  expect(buildOrder(n, deps)).toEqual([]);\n});\n"},{"lang":"python","runner":"browser","starter":"def build_order(n: int, dependencies: list[list[int]]) -> list[int]:\n    \"\"\"A build order of modules 0..n-1; [a, b] means \"a depends on b\" (b first).\n    Returns [] when the dependencies contain a cycle.\"\"\"\n    raise NotImplementedError\n","testCount":7,"tests":"def assert_valid_order(n, dependencies, order):\n    assert len(order) == n, f\"expected {n} modules, got {len(order)}\"\n    position = [-1] * n\n    for i, m in enumerate(order):\n        assert isinstance(m, int) and 0 <= m < n and position[m] == -1, f\"module {m} is invalid or repeated\"\n        position[m] = i\n    for a, b in dependencies:\n        assert position[b] < position[a], f\"module {a} is built before its dependency {b}\"\n\n\ndef test_chain_has_exactly_one_order():\n    got = build_order(3, [[1, 0], [2, 1]])\n    assert got == [0, 1, 2], f\"expected [0, 1, 2], got {got}\"\n\n\ndef test_diamond():\n    deps = [[1, 0], [2, 0], [3, 1], [3, 2]]\n    assert_valid_order(4, deps, build_order(4, deps))\n\n\ndef test_modules_without_dependencies_are_included():\n    assert_valid_order(3, [], build_order(3, []))\n    assert_valid_order(5, [[2, 0]], build_order(5, [[2, 0]]))\n\n\ndef test_cycles_give_an_empty_list():\n    for n, deps in ((2, [[0, 1], [1, 0]]), (3, [[0, 0]]), (4, [[1, 0], [2, 3], [3, 2]]), (3, [[0, 1], [1, 2], [2, 0]])):\n        got = build_order(n, deps)\n        assert got == [], f\"build_order({n}, {deps}): expected [], got {got}\"\n\n\ndef test_repeated_dependencies():\n    deps = [[1, 0], [1, 0], [2, 1], [2, 0], [2, 1]]\n    assert_valid_order(3, deps, build_order(3, deps))\n\n\ndef test_single_module():\n    got = build_order(1, [])\n    assert got == [0], f\"expected [0], got {got}\"\n\n\ndef test_performance_100k_modules():\n    n = 100_000\n    deps = []\n    for i in range(1, n):\n        deps.append([i, i - 1])\n        deps.append([i, i >> 1])\n    assert_valid_order(n, deps, build_order(n, deps))\n    deps.append([0, n - 1])\n    got = build_order(n, deps)\n    assert got == [], f\"a cycle through all modules: expected [], got a list of {len(got)}\"\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\n\npublic static class Solution\n{\n    /// <summary>A build order of modules 0..n-1; {a, b} means \"a depends on b\" (b first). Empty array on a cycle.</summary>\n    public static int[] BuildOrder(int n, int[][] dependencies)\n    {\n        throw new NotImplementedException();\n    }\n}\n","testCount":7},{"lang":"java","runner":"judge0","starter":"class Solution {\n    /** A build order of modules 0..n-1; {a, b} means \"a depends on b\" (b first). Empty array on a cycle. */\n    static int[] buildOrder(int n, int[][] dependencies) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":7},{"lang":"go","runner":"judge0","starter":"package main\n\n// BuildOrder returns a build order of modules 0..n-1; {a, b} means \"a depends on b\" (b first).\n// It returns an empty slice when the dependencies contain a cycle.\nfunc BuildOrder(n int, dependencies [][]int) []int {\n\tpanic(\"not implemented\")\n}\n","testCount":7}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:53.390Z","requestedLang":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Narzędzie do budowania monorepo (jak Nx, Bazel czy Gradle) musi zbudować każdy moduł "},{"type":"text","text":"po","marks":[{"type":"bold"}]},{"type":"text","text":" modułach, od których zależy. Moduły mają numery "},{"type":"text","text":"0 … n-1","marks":[{"type":"code"}]},{"type":"text","text":", a para "},{"type":"text","text":"[a, b]","marks":[{"type":"code"}]},{"type":"text","text":" oznacza: „"},{"type":"text","text":"a","marks":[{"type":"code"}]},{"type":"text","text":" zależy od "},{"type":"text","text":"b","marks":[{"type":"code"}]},{"type":"text","text":"”, czyli "},{"type":"text","text":"b","marks":[{"type":"code"}]},{"type":"text","text":" trzeba zbudować przed "},{"type":"text","text":"a","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"paragraph","content":[{"type":"text","text":"Funkcja zwraca listę wszystkich "},{"type":"text","text":"n","marks":[{"type":"code"}]},{"type":"text","text":" modułów w kolejności, w której można je zbudować (każdy moduł występuje dokładnie raz, a każda zależność jest zbudowana wcześniej). Jeśli takiej kolejności nie ma (zależności tworzą "},{"type":"text","text":"cykl","marks":[{"type":"bold"}]},{"type":"text","text":", także "},{"type":"text","text":"[a, a]","marks":[{"type":"code"}]},{"type":"text","text":"), zwraca pustą listę."}]},{"type":"paragraph","content":[{"type":"text","text":"Poprawnych kolejności bywa wiele – testy akceptują każdą z nich."}]},{"type":"paragraph","content":[{"type":"text","text":"Sygnatury: "},{"type":"text","text":"buildOrder(n, dependencies)","marks":[{"type":"code"}]},{"type":"text","text":" (JS/TS), "},{"type":"text","text":"build_order(n, dependencies)","marks":[{"type":"code"}]},{"type":"text","text":" (Python), "},{"type":"text","text":"Solution.BuildOrder","marks":[{"type":"code"}]},{"type":"text","text":" (C#, "},{"type":"text","text":"int[][]","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"Solution.buildOrder","marks":[{"type":"code"}]},{"type":"text","text":" (Java, "},{"type":"text","text":"int[][]","marks":[{"type":"code"}]},{"type":"text","text":"), "},{"type":"text","text":"BuildOrder","marks":[{"type":"code"}]},{"type":"text","text":" (Go, "},{"type":"text","text":"[][]int","marks":[{"type":"code"}]},{"type":"text","text":")."}]},{"type":"heading","attrs":{"level":2,"id":"przyklady"},"content":[{"type":"text","text":"Przykłady"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"n","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"dependencies","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Przykładowy wynik"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"3","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[[1, 0], [2, 1]]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[0, 1, 2]","marks":[{"type":"code"}]},{"type":"text","text":" – jedyna możliwość"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"4","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[[1, 0], [2, 0], [3, 1], [3, 2]]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[0, 1, 2, 3]","marks":[{"type":"code"}]},{"type":"text","text":" albo "},{"type":"text","text":"[0, 2, 1, 3]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"3","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"dowolna permutacja, np. "},{"type":"text","text":"[0, 1, 2]","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"2","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[[0, 1], [1, 0]]","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"[]","marks":[{"type":"code"}]},{"type":"text","text":" – cykl"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"ograniczenia"},"content":[{"type":"text","text":"Ograniczenia"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"1 ≤ n ≤ 100 000","marks":[{"type":"code"}]},{"type":"text","text":", do 200 000 zależności, mogą się powtarzać."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Łańcuch zależności może mieć długość 100 000 – rekurencyjne DFS przepełni stos."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"oczekiwana-zlozonosc"},"content":[{"type":"text","text":"Oczekiwana złożoność"}]},{"type":"paragraph","content":[{"type":"text","text":"Czas "},{"type":"text","text":"O(V + E)","marks":[{"type":"bold"}]},{"type":"text","text":", pamięć "},{"type":"text","text":"O(V + E)","marks":[{"type":"bold"}]},{"type":"text","text":"."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"leetcode","url":"https://leetcode.com/problems/course-schedule-ii/","title":"LeetCode 210 – Course Schedule II","difficulty":null}],"articles":[],"topicsInfo":[],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:53.392Z","updatedAt":"2026-11-27T08:22:53.392Z"}