Skip to content

components and component_mapping methods can be speed up by a factor of len(distinct_roots) #2

@ismael-elatifi

Description

@ismael-elatifi

When you group elements into components (in methods components and component_mapping), the time complexity of your current way of doing it is O(N x M) (where N is len(self._elts) and M is len(distinct_roots)).
O(N x M) because looping over distinct roots is O(M) and boolean indexing over elements elts[roots == root] is O(N).
The optimized code below using a defaultdict (hashmap) has time complexity O(N). The higher M is, the bigger is the speed up.

from collections import defaultdict

def components(self):
	dict_components = defaultdict(list)
	for elem in self._elts:
		root = self.find(elem)
		dict_components[root].append(elem)
	return dict_components

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions