diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 2a6c4aa1..5b38cdf8 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -88,6 +88,7 @@ | 647 | [Palindromic Substring](https://leetcode.com/problems/palindromic-substrings/) | [C](./src/647.c) | Medium | | 669 | [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [C](./src/669.c) | Medium | | 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [C](./src/674.c) | Easy | +| 684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection/description/) | [C](./src/684.c) | Medium | | 700 | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [C](./src/700.c) | Easy | | 701 | [Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree/) | [C](./src/701.c) | Medium | | 704 | [Binary Search](https://leetcode.com/problems/binary-search/) | [C](./src/704.c) | Easy | diff --git a/leetcode/src/684.c b/leetcode/src/684.c new file mode 100644 index 00000000..e5de7faa --- /dev/null +++ b/leetcode/src/684.c @@ -0,0 +1,49 @@ +/** + * Note: The returned array must be malloced, assume caller calls free(). + */ +int find(int* sets, int index){ + while (sets[index] != index){ + index = sets[index]; + } + + return index; +} + +void unionSet(int* sets, int i1, int i2){ + int i1Parent = find(sets, i1); + int i2Parent = find(sets, i2); + + sets[i1Parent] = i2Parent; +} + +// Union find +// Runtime: O(n) +// Space: O(n) +int* findRedundantConnection(int** edges, int edgesSize, int* edgesColSize, int* returnSize){ + int setsSize = edgesSize + 1; + int* sets = malloc(setsSize * sizeof(int)); + for (int i = 0; i < setsSize; i++){ + sets[i] = i; + } + + int* result = malloc(2 * sizeof(int)); + *returnSize = 2; + + for (int i = 0; i < edgesSize; i++){ + int* edge = edges[i]; + + int i0Parent = find(sets, edge[0]); + int i1Parent = find(sets, edge[1]); + + if (i0Parent == i1Parent){ + result[0] = edge[0]; + result[1] = edge[1]; + continue; + } + + unionSet(sets, i0Parent, i1Parent); + } + + free(sets); + return result; +}