I have an AoC
problem where I have been given the data below:
data = """2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8"""
I need to find the number of pairs which fully contain another pair. For example, 2-8
fully contains 3-7
, and 6-6
is fully contained by 4-6
.
I have solved it using the below code:
def aoc_part1(self, data):
counter = 0
for lines_data in data.splitlines():
lines_data = lines_data.strip()
first_range, second_range = self.__get_first_second_list_of_elements(lines_data)
check_first_side_if_returns_true = all(item in first_range for item in second_range)
check_second_side_if_returns_true = all(item in second_range for item in first_range)
if check_first_side_if_returns_true or check_second_side_if_returns_true:
counter += 1
return counter
def __get_first_second_list_of_elements(self, data):
first_elf, second_elf = data.split(",")[0], data.split(",")[1]
first_range_start, first_range_end = map(int, first_elf.split("-"))
second_range_start, second_range_end = map(int, second_elf.split("-"))
first_range = list(range(first_range_start, first_range_end + 1))
second_range = list(range(second_range_start, second_range_end + 1))
return first_range, second_range
I was just wondering about the time complexity here. I think it should be a brute force
here because for every iteration all
will run another loop. How can I optimize this solution in order to get linear time complexity?
first_range
and second_range
are of int
types. check_first_side_if_returns_true
and check_second_side_if_returns_true
are the boolean
variables that check if the list is entirely contained or not. Based on that, it returns True
or False
.