
Sponsored
Sponsored
This approach considers the integer array as a graph where each index is a node. We connect nodes i and j if gcd(nums[i], nums[j]) > 1. Using a union-find data structure, we efficiently manage connected components as we establish connections among indices. The goal is to determine whether all indices are part of a single connected component.
The time complexity is O(n^2 * log*(n)), due to the nested for loops for each pair of numbers, where log* is the inverse Ackermann function that represents the amortized time of the union-find operations. The space complexity is O(n) for storing the union-find array.
1import java.util.*;
2
3class UnionFind {
4 private int[] root;
5 private int[] rank;
6
7 public UnionFind(int size) {
8 root = new int[size];
9 rank = new int[size];
10 for (int i = 0; i < size; i++) {
11 root[i] = i;
12 rank[i] = 1;
13 }
14 }
15
16 public int find(int x) {
17 if (x == root[x]) {
18 return x;
19 }
20 return root[x] = find(root[x]);
21 }
22
23 public void union(int x, int y) {
24 int rootX = find(x);
25 int rootY = find(y);
26 if (rootX != rootY) {
27 if (rank[rootX] > rank[rootY]) {
28 root[rootY] = rootX;
29 } else if (rank[rootX] < rank[rootY]) {
30 root[rootX] = rootY;
31 } else {
32 root[rootY] = rootX;
33 rank[rootX]++;
34 }
35 }
36 }
37}
38
39public class Solution {
40 public boolean canTraverseAllPairs(int[] nums) {
41 int n = nums.length;
42 UnionFind uf = new UnionFind(n);
43
44 for (int i = 0; i < n; i++) {
45 for (int j = i + 1; j < n; j++) {
46 if (gcd(nums[i], nums[j]) > 1) {
47 uf.union(i, j);
48 }
49 }
50 }
51 int root = uf.find(0);
52 for (int i = 1; i < n; i++) {
53 if (uf.find(i) != root) {
54 return false;
55 }
56 }
57 return true;
58 }
59
60 private int gcd(int a, int b) {
61 while (b != 0) {
62 int temp = b;
63 b = a % b;
64 a = temp;
65 }
66 return a;
67 }
68
69 public static void main(String[] args) {
70 Solution sol = new Solution();
71 int[] nums = {2, 3, 6};
72 System.out.println(sol.canTraverseAllPairs(nums));
73 }
74}
75This Java solution uses a Union-Find class to connect indices based on the condition gcd(<i>, <j>) > 1. After constructing the graph, it checks for a single connected component.
In this approach, the solution represents the integer array as an adjacency list graph. Each index is considered as a node, and we link them with edges if their GCD is greater than 1. We perform a depth-first search (DFS) or breadth-first search (BFS) to determine the connectivity of the nodes. If all indices are reachable from any starting index, the traversal is possible.
The time complexity is O(n^2), and the space complexity also is O(n^2) due to the adjacency matrix representation.
The Python code represents the array as an adjacency list graph, performing DFS to check whether all nodes are reachable from the first one, verifying the traversal capability between indices.