Google Interview Question
Software EngineersCountry: United States
Here is a relatively simple O(n^2) solution that iterates over pairs of horizontal and vertical line segments. Not sure how to improve the solution.
# -*- coding: utf-8 -*-
from typing import List, Tuple, Optional, Dict
Segment = Tuple[str, int, int, int]
# line segment is represented by ({V|H}, intercept, start, end), where
# 1. {V|H} represented where the line is Vertical or Horizontal,
# 2. intercept is the x-intercept for vertical line segment, and the y-intercept
# for the horizontal line segment.
# 3. start is the y-axis start of the line segment for vertical, and the x-axis
# start for the horizontal line segment.
# 4. end is analogous to start
# sort the line segments into vertical and horizontal, and sort them by their
# intercepts.
def sort_line_segments(line_segments: List[Segment]) -> Tuple[List[Segment], List[Segment]]:
vertical_segments = list(filter(lambda s: s[0] == 'V', line_segments))
horizontal_segments = list(filter(lambda s: s[0] == 'H', line_segments))
return (sorted(vertical_segments), sorted(horizontal_segments))
# stores the line segments in a dict keyed by its intercept.
def create_segment_dict(segments: List[Segment]) -> Dict[Tuple[str, int], Segment]:
return {(s[0], s[1]): s for s in segments}
def get_intersection(v_segment: Segment, h_segment: Segment) -> Optional[Tuple[int, int]]:
# assuming the two are vertical and horizontal segments.
if ((h_segment[2] <= v_segment[1] <= h_segment[3]) and
(v_segment[2] <= h_segment[1] <= v_segment[3])):
return (v_segment[1], h_segment[1])
return None
import itertools
def count_squares(segments: List[Segment]) -> int:
square_count = 0
v_segments, h_segments = sort_line_segments(segments)
v_dict = create_segment_dict(v_segments)
v_len = len(v_segments)
h_len = len(h_segments)
for (v_index, h_index) in itertools.product(range(v_len), range(h_len)):
v_segment = v_segments[v_index]
h_segment = h_segments[h_index]
intersection = get_intersection(v_segment, h_segment)
# print(f"intersection is {intersection}")
if intersection is None:
continue
# we have an intersection point. Check if we have another horizontal segment
# that intersects with v_segments[v_index]
for h_index2 in range(h_index+1, h_len):
h_segment2 = h_segments[h_index2]
intersection2 = get_intersection(v_segment, h_segment2)
# print(f"intersection2 is {intersection2}")
if intersection2 is None:
continue
# We have a second intersection point on the vertical line segment.
# length of the line segments between these two points is the length
# of a square, it exists.
square_length = h_segment2[1] - h_segment[1]
# print(f"Square_length is {square_length}")
# The vertices of the square are `intersection` and `intersection2` on
# the same vertical line segment.
# If a square exists, then there must be another vertical line segment
# ('V', v_segment[1] + square_length, <=h_segment[1], >= h_segment2[1])
if ('V', v_segment[1] + square_length) not in v_dict:
continue
v_segment2 = v_dict[('V', v_segment[1] + square_length)]
# print(f"v2 is {v_segment2}")
if (v_segment2[2] <= h_segment[1]) and (v_segment2[3] >= h_segment2[1]):
# Found a square
# print(f" Found {square_length} square {v_segment}, {v_segment2}, {h_segment}, {h_segment2}")
square_count += 1
return square_count
segments = [('V', 0, 2, 8),
('H', 3, 0, 2),
('V', 2, 3, 7),
('H', 5, -1, 3)]
assert count_squares(segments) == 1
segments = [
('V', 10, 5, 15), ('V', 10, 15, 25),
('V', 20, 5, 15), ('V', 20, 15, 25),
('H', 10, 5, 15), ('H', 10, 15, 25),
('H', 20, 5, 15), ('H', 20, 15, 25)
]
assert count_squares(segments) == 0
segments = [
('V', 5, 0, 20), ('V', 10, 0, 20), ('V', 15, 0, 20), ('V', 20, 0, 20),
('H', 5, 0, 25), ('H', 10, 0, 25)
]
assert count_squares(segments) == 3
segments = [
('V', 5, 0, 20), ('V', 10, 0, 20), ('V', 15, 0, 20), ('V', 20, 0, 20),
('H', 5, 0, 25), ('H', 10, 0, 25), ('H', 20, 0, 25)
]
assert count_squares(segments) == 6
Complexity - O(mn)
M: Number of vertical lines
N: Number of horizontal lines
class Line():
def __init__(self, y1, y2, x1, x2, direction):
self.y1 = y1
self.y2 = y2
self.x1 = x1
self.x2 = x2
self.direction = direction
def getLength(self):
return int(((self.x1 - self.x2)**2 + (self.y1 - self.y2)**2)**0.5)
def matchLinePairs(linePairOne, linePairTwo):
lineOne, lineTwo = linePairOne
lineThree, lineFour = linePairTwo
if lineOne.getLength() == lineThree.getLength():
if (lineOne.x1, lineOne.y1) == (lineThree.x1, lineThree.y1) or (lineOne.x1, lineOne.y1) == (lineThree.x2, lineThree.y2):
return True
return False
def numberOfSquares(aListOfVertLines, aListOfHorLines):
horPairs = []
verPairs = []
for i in range(len(aListOfHorLines)):
line1 = aListOfHorLines[i]
for j in range(i, len(aListOfHorLines)):
line2 = aListOfHorLines[j]
if line1.getLength() == line2.getLength():
if line1.y1 == line2.y1 and line1.y2 == line2.y2:
horPairs.append((line1, line2))
for i in range(len(aListOfVertLines)):
line1 = aListOfVertLines[i]
for j in range(i, len(aListOfVertLines)):
line2 = aListOfHorLines[j]
if line1.getLength() == line2.getLength():
if line1.x1 == line2.x1 and line1.x2 == line2.x2:
verPairs.append((line1, line2))
numSquares = 0
for horLinePair in horPairs:
for verLinePair in verPairs:
if matchLinePairs(horLinePair, verLinePair):
numSquares+=1
return numSquares
For every pair of horizontal segments, if they have different y-intercepts, and if their x-ranges overlap, calculate the y-distance between them and add that to a hash map of distance to pairs of segments. O(n^2)
For every pair of vertical segments, if they have different x-intercepts, and their y-ranges overlap, calculate the x-distance between them. Look up this distance in the hash map, if it exists, check each of the corresponding pairs of horizontal lines to see if all four segments cross each other. O(n^2), or worst case O(n^3) when all the segments have the same range and are equally spaced.
I am assuming that all the line segments are distinct.
Hash map all pairs of horizontal segments with overlapping ranges by the distance between them. for example {5: [((10, 20, 4, H), (19, 21, 9, H))]}. This is O(n^2)
For all pairs of vertical segments with overlapping ranges, get the distance between them, look up this distance in the hash map, and for each pair of horizontal segments found there (if any), check if the intersect the vertical pair to form a square. O(n^2) generally, worst case O(n^3) when all segments are the same range and equidistant.
Here's my solution, assuming we are trying to find all possible boxes from a list of horizontal and vertical lines. I use separate HorizontalLine and VerticalLine classes for convenience.
This is O(n^2) in the number of horizontal lines, O(n^2) in the number of vertical lines, and then O(n_overlap) in the number of overlaps.
from typing import List, Tuple
class HorizontalLine:
"""
A class representing a horizontal line
"""
def __init__(self, x1: float, x2: float, y: float):
self.x1 = x1
self.x2 = x2
self.y = y
class VerticalLine:
"""
A class representing a vertical line
"""
def __init__(self, x: float, y1: float, y2: float):
self.x = x
self.y1 = y1
self.y2 = y2
class Overlap:
"""
A class representing the overlap between two horizontal or two vertical lines
"""
def __init__(self, x1: float, x2: float, y1: float, y2: float):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
def find_horizontal_overlap(h1: HorizontalLine, h2: HorizontalLine) -> Tuple[bool, Overlap]:
# finds the overlap, as an Overlap object, between two horizontal lines. Returns a bool with whether not an overlap
# exists between the two lines, and the overlap. The overlap is only meaningful if the bool is True.
if min(h1.x2, h2.x2) > max(h1.x1, h2.x1):
return True, Overlap(max(h1.x1, h2.x1), min(h1.x2, h2.x2), min(h1.y, h2.y), max(h1.y, h2.y))
else:
return False, Overlap(0, 0, 0, 0)
def find_vertical_overlap(v1: VerticalLine, v2: VerticalLine) -> Tuple[bool, Overlap]:
# finds the overlap, as an Overlap object, between two vertical lines. Returns a bool with whether not an overlap
# exists between the two lines, and the overlap. The overlap is only meaningful if the bool is True.
if min(v1.y2, v2.y2) > max(v1.y1, v2.y1):
return True, Overlap(min(v1.x, v2.x), max(v1.x, v2.x), max(v1.y1, v2.y1), min(v1.y2, v2.y2))
else:
return False, Overlap(0, 0, 0, 0)
def box_exists(ho: Overlap, vo: Overlap) -> bool:
# check the condition for a box to exist given a horizontal overlap object and a vertical overlap object
return ho.x1 <= vo.x1 and ho.x2 >= vo.x2 and vo.y1 <= ho.y1 and vo.y2 >= ho.y2
def count_boxes(horizontal_lines: List[HorizontalLine], vertical_lines: List[VerticalLine]) -> int:
# Counts the number of boxes from a list of horizontal and a list of vertical lines
# get number of lines in each list, for convenience
n_horizontal = len(horizontal_lines)
n_vertical = len(vertical_lines)
# check the necessary condition on the number of lines
if n_horizontal < 2 or n_vertical < 2:
return 0
# find all horizontal overlaps and vertical overlaps
horizontal_overlaps = []
for i in range(n_horizontal):
for j in range(i + 1, n_horizontal):
overlap_found, ho = find_horizontal_overlap(horizontal_lines[i], horizontal_lines[j])
if overlap_found:
horizontal_overlaps.append(ho)
vertical_overlaps = []
for i in range(n_vertical):
for j in range(i + 1, n_vertical):
overlap_found, vo = find_vertical_overlap(vertical_lines[i], vertical_lines[j])
if overlap_found:
vertical_overlaps.append(vo)
# iterate over all horizontal and vertical overlaps, and find the number of boxes which are possible
num_boxes = 0
for ho in horizontal_overlaps:
for vo in vertical_overlaps:
if box_exists(ho, vo):
num_boxes += 1
return num_boxes
if __name__ == '__main__':
horizontal_lines = [HorizontalLine(0.5, 2.5, 1), HorizontalLine(-1, 1, 2), HorizontalLine(1, 3, 1.5)]
vertical_lines = [VerticalLine(1, 1, 2.5), VerticalLine(2, -1, 1.5), VerticalLine(1.5, 0, 3)]
print(count_boxes(horizontal_lines, vertical_lines))
from typing import List, Tuple
class HorizontalLine:
"""
A class representing a horizontal line
"""
def __init__(self, x1: float, x2: float, y: float):
self.x1 = x1
self.x2 = x2
self.y = y
class VerticalLine:
"""
A class representing a vertical line
"""
def __init__(self, x: float, y1: float, y2: float):
self.x = x
self.y1 = y1
self.y2 = y2
class Overlap:
"""
A class representing the overlap between two horizontal or two vertical lines
"""
def __init__(self, x1: float, x2: float, y1: float, y2: float):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
def find_horizontal_overlap(h1: HorizontalLine, h2: HorizontalLine) -> Tuple[bool, Overlap]:
# finds the overlap, as an Overlap object, between two horizontal lines. Returns a bool with whether not an overlap
# exists between the two lines, and the overlap. The overlap is only meaningful if the bool is True.
if min(h1.x2, h2.x2) > max(h1.x1, h2.x1):
return True, Overlap(max(h1.x1, h2.x1), min(h1.x2, h2.x2), min(h1.y, h2.y), max(h1.y, h2.y))
else:
return False, Overlap(0, 0, 0, 0)
def find_vertical_overlap(v1: VerticalLine, v2: VerticalLine) -> Tuple[bool, Overlap]:
# finds the overlap, as an Overlap object, between two vertical lines. Returns a bool with whether not an overlap
# exists between the two lines, and the overlap. The overlap is only meaningful if the bool is True.
if min(v1.y2, v2.y2) > max(v1.y1, v2.y1):
return True, Overlap(min(v1.x, v2.x), max(v1.x, v2.x), max(v1.y1, v2.y1), min(v1.y2, v2.y2))
else:
return False, Overlap(0, 0, 0, 0)
def box_exists(ho: Overlap, vo: Overlap) -> bool:
# check the condition for a box to exist given a horizontal overlap object and a vertical overlap object
return ho.x1 <= vo.x1 and ho.x2 >= vo.x2 and vo.y1 <= ho.y1 and vo.y2 >= ho.y2
def count_boxes(horizontal_lines: List[HorizontalLine], vertical_lines: List[VerticalLine]) -> int:
# Counts the number of boxes from a list of horizontal and a list of vertical lines
# get number of lines in each list, for convenience
n_horizontal = len(horizontal_lines)
n_vertical = len(vertical_lines)
# check the necessary condition on the number of lines
if n_horizontal < 2 or n_vertical < 2:
return 0
# find all horizontal overlaps and vertical overlaps
horizontal_overlaps = []
for i in range(n_horizontal):
for j in range(i + 1, n_horizontal):
overlap_found, ho = find_horizontal_overlap(horizontal_lines[i], horizontal_lines[j])
if overlap_found:
horizontal_overlaps.append(ho)
vertical_overlaps = []
for i in range(n_vertical):
for j in range(i + 1, n_vertical):
overlap_found, vo = find_vertical_overlap(vertical_lines[i], vertical_lines[j])
if overlap_found:
vertical_overlaps.append(vo)
# iterate over all horizontal and vertical overlaps, and find the number of boxes which are possible
num_boxes = 0
for ho in horizontal_overlaps:
for vo in vertical_overlaps:
if box_exists(ho, vo):
num_boxes += 1
return num_boxes
if __name__ == '__main__':
horizontal_lines = [HorizontalLine(0.5, 2.5, 1), HorizontalLine(-1, 1, 2), HorizontalLine(1, 3, 1.5)]
vertical_lines = [VerticalLine(1, 1, 2.5), VerticalLine(2, -1, 1.5), VerticalLine(1.5, 0, 3)]
print(count_boxes(horizontal_lines, vertical_lines))
Hi All,
- uj.us October 07, 2019Question is about line segments not the lines. Each line segment is represented with the start and their end points and the intercept point on the axis. And another boolean to represent if the line segment is horizontal or vertical.
Example: 10 20 5 V represents a line which is vertical and its x-intercept is 5 and start from 10 and ends at 20 ie., points are (5, 10) (5, 20) represents the line