Google Interview Question for Software Engineers


Country: United States




Comment hidden because of low score. Click to expand.
0
of 0 vote

Hi All,

Question 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

- uj.us October 07, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

int findNumOfSquares(int h, int v){
 int result; 
 if(h < 2 && v < 2 ){
   return result;
 }
 else{
  result =  1  + findNumOfSquares(v-2,h-2)
}
return result;
}

- novastorm123 October 16, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

- Anonymous November 25, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Sorry, this is not O(n^2), but O(n^3).

- Anonymous November 26, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

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

- sleebapaul January 28, 2020 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

h = int(input("Enter number of horizontal lines : "))
v = int(input("Enter number of vertical lines : "))
result = 0
small = min(h,v)
for i in range(-1,small):
result += ((h-i)*(v-i))
print("Number of squares : ", result)

- can it be simplified? October 04, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

h = int(input("Enter number of horizontal lines : "))
v = int(input("Enter number of vertical lines : "))
result = 0
small = min(h,v)
for i in range(-1,small):
    result += ((h-i)*(v-i))
print("Number of squares : ", result)

- can it be simplified? October 04, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

h = int(input("Enter number of horizontal lines : "))
v = int(input("Enter number of vertical lines : "))
result = 0
small = min(h,v)
for i in range(-1,small):
    result += ((h-i)*(v-i))
print("Number of squares : ", result)

- can_it_be_simplified October 04, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

h = int(input("Enter number of horizontal lines : "))
v = int(input("Enter number of vertical lines : "))
result = 0
small = min(h,v)
for i in range(-1,small):
    result += ((h-i)*(v-i))
print("Number of squares : ", result)

- can it be simplified? October 04, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

h= int(input(“Enter the number of horizontal lines:”))
v= int(input(“Enter the number of vertical lines:”)
def maxsquares(h,v):
squares=(h-1)*(v-1)
return squares
maxsquares(h,v)

- Anonymous October 05, 2019 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

int findNumberOfSquares(int h, int v) {
	int min = Math.min(h,v);
	int num = min / 2;
	return min;

}

- Dave October 09, 2019 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More