Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the parent array where each element is its own parent.
DSA Python
parent = [i for i in range([1])]
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or 1 instead of the number of elements for range.
Using length of parent before it is defined.
✗ Incorrect
We create a list where each element is its own parent, so we use the size 'n' to range over all elements.
2fill in blank
mediumComplete the code to find the root parent of element x with path compression.
DSA Python
def find(x): if parent[x] != x: parent[x] = [1](parent[x]) return parent[x]
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'union' instead of 'find' inside the function.
Assigning parent[x] to x directly without recursion.
✗ Incorrect
The find function calls itself recursively to find the root parent and compresses the path by updating parent[x].
3fill in blank
hardFix the error in the union function to correctly merge two sets by their root parents.
DSA Python
def union(a, b): rootA = find(a) rootB = find(b) if rootA != rootB: parent[[1]] = rootB
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'a' or 'b' instead of their root parents.
Assigning parent of rootB instead of rootA.
✗ Incorrect
We assign the parent of rootA to rootB to merge the two sets correctly.
4fill in blank
hardFill both blanks to check if two elements are in the same set.
DSA Python
def connected(x, y): return find([1]) == find([2])
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'parent' or 'root' instead of the elements.
Comparing elements directly without finding their roots.
✗ Incorrect
We check if the root parents of x and y are the same to determine if they are connected.
5fill in blank
hardFill all three blanks to implement union by rank optimization.
DSA Python
def union(a, b): rootA = find(a) rootB = find(b) if rootA != rootB: if rank[rootA] < [1]: parent[rootA] = rootB elif rank[rootA] > [2]: parent[rootB] = rootA else: parent[rootB] = rootA rank[rootA] += [3]
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing rank[rootA] with rank[rootA] instead of rank[rootB].
Increasing rank by a value other than 1.
Using rank[a] instead of rank[rootB].
✗ Incorrect
We compare rank[rootA] with rank[rootB] to decide which root becomes parent, and increase rank by 1 when ranks are equal.
