https://github.com/Premiumlab/Python-for-Algorithms--Data-Structures--and-Interviews/blob/master/Mock%20Interviews/Large%20E-Commerce%20Company/E-Commerce%20Company%20-%20Interview%20Problems%20-%20SOLUTIONS/On-Site%20Question%203%20-%20SOLUTION.ipynb

On-Site Question 3 - SOLUTION

Problem

Given two rectangles, determine if they overlap. The rectangles are defined as a Dictionary, for example:

In [2]:
r1 = {

         # x and y coordinates of the bottom-left corner of the rectangle
'x': 2 , 'y': 4, # Width and Height of rectangle
'w':5,'h':12}
 

If the rectangles do overlap, return the dictionary which describes the overlapping section

 

Requirements

Make sure the dictionary you output is in the same form as the input.

Feel free to use an IDE for the code, but make sure you use paper/pencil or whiteboard to draw out your plan and logic

 

Solution

This is a problem where it helps a lot to draw out your thinking. There are a few things we will need to think about:

  • How can we determine an intersection?
  • What if a rectangle is fully inside another rectangle?
  • What if there is no intersection, but the rectangles share an edge?

The key to solving this problem is to break it up in to sub-problems. We can split up the problem into an x-axis problem and a y-axis problem.

We will create a function that can detect overlap in 1 dimension. Then we will split the rectangles into x and width, and y and height components. We can then determine that if there is overlap on both dimensions, then the rectangles themselves intersect!

In order to understand the calc_overlap function, draw out two flat lines and follow along with the function and notice how it detects an overlap!

Let's begin by creating a general function to detect overlap in a single dimension:


def calc_overlap(coor1,dim1,coor2,dim2):
"""
Takes in 2 coordinates and their length in that dimension
""" # Find greater of the two coordinates
# (this is either the point to the most right
# or the higher point, depending on the dimension) # The greater point would be the start of the overlap
greater = max(coor1,coor2) # The lower point is the end of the overlap
lower = min(coor1+dim1,coor2+dim2) # Return a tuple of Nones if there is no overlap if greater >= lower:
return (None,None) # Otherwise, get the overlap length
overlap = lower-greater return (greater,overlap)

 

Now let's use this function to detect if the rectangles overlap!

 
 
def calc_rect_overlap(r1,r2):

    x_overlap, w_overlap = calc_overlap(r1['x'],r1['w'],r2['x'],r2['w'])

    y_overlap, h_overlap = calc_overlap(r1['y'],r1['h'],r2['y'],r2['h'])

    # If either returned None tuples, then there is no overlap!
if not w_overlap or not h_overlap:
print 'There was no overlap!'
return None # Otherwise return the dictionary format of the overlapping rectangle
return { 'x':x_overlap,'y': y_overlap,'w':w_overlap,'h':h_overlap}
 
 

Our solution is O(1) for both time and space! Let's see it in action:

In [5]:
r1 = {'x': 2 , 'y': 4,'w':5,'h':12}
r2 = {'x': 1 , 'y': 5,'w':7,'h':14}
calc_rect_overlap(r1,r2)
Out[5]:
{'h': 11, 'w': 5, 'x': 2, 'y': 5}
 

Make sure to review the answer and practice writing it out by hand!

Good Job!

Determine overlapping rectangles的更多相关文章

  1. Overlapping rectangles判断两个矩形是否重叠的问题 C++

    Given two rectangles, find if the given two rectangles overlap or not. A rectangle is denoted by pro ...

  2. 2017ICPC南宁赛区网络赛 Overlapping Rectangles(重叠矩阵面积和=离散化模板)

    There are nnn rectangles on the plane. The problem is to find the area of the union of these rectang ...

  3. 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛 Overlapping Rectangles

    There are nn rectangles on the plane. The problem is to find the area of the union of these rectangl ...

  4. 2017 ACM/ICPC 南宁区 网络赛 Overlapping Rectangles

    2017-09-24 20:11:21 writer:pprp 找到的大神的代码,直接过了 采用了扫描线+线段树的算法,先码了,作为模板也不错啊 题目链接:https://nanti.jisuanke ...

  5. 计蒜客 Overlapping Rectangles (离散化)

    题意: 给定一个坐标系, 给出n个矩形的左下角坐标(bx,by)和右上角坐标(tx,ty) , 求矩形覆盖的面积, 有些区域会被多个矩形覆盖, 但只用算一次. n <= 1000,  0 < ...

  6. 2017 icpc 南宁网络赛

    2000年台湾大专题...英语阅读输入输出专场..我只能说很强势.. M. Frequent Subsets Problem The frequent subset problem is define ...

  7. 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛

    02Train Seats Reservation 问答 只看题面 33.87% 1000ms 131072K You are given a list of train stations, say ...

  8. 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛 (B,F,L,M)

    B. Train Seats Reservation You are given a list of train stations, say from the station 1 to the sta ...

  9. R绘图基础

    一,布局 R绘图所占的区域,被分成两大部分,一是外围边距,一是绘图区域. 外围边距可使用par()函数中的oma来进行设置.比如oma=c(4,3,2,1),就是指外围边距分别为下边距:4行,左边距3 ...

随机推荐

  1. js1:根据标签的Id获取value值

    例子:<input id="startDate" name="startDate" value="2015-09-14" class= ...

  2. leetcode210

    public class Solution { //test case [1,0] public int[] findOrder(int numCourses, int[][] prerequisit ...

  3. NavitForMySql 破解工具使用

    Navicat 11.0注册机使用教程: 1.右键-管理员权限运行注册机2.选择对应的产品3.点击“补丁”按钮,选择文件4.点击“生成”按钮,生成序列号,并保存下授权文件5.复制序列号,打开软件,在弹 ...

  4. 简单ssh建立 (paramiko)

    SSH为建立在应用层和传输层基础上的安全协议.SSH是目前较可靠,专为远程登录会话和其他网络服务提供安全性的协议.利用SSH协议可以有效防止远程管理过程中的信息泄露问题. import paramik ...

  5. AS3中String转换成Boolean

    AS3中, 对布尔值的转换, 规定所有的非空字符串都是true. 下面都不行: var f:Boolean = new Boolean(str); var f:Boolean = str as Boo ...

  6. 五种方法实现Java的Singleton单例模式

    面试的时候经常会问到Java的单例模式,这道题能很好的考察候选人对知识点的理解程度.单例模式要求在系统运行时,只存在唯一的一个实例对象. 下面我们来详细剖析一下其中的关键知识点,并介绍五种实现方法,以 ...

  7. Python之关系字段

    参考:https://blog.csdn.net/pugongying1988/article/details/72870264 关系字段:一对一,多对一,多对多 一对一:  现在有很多一对一辅导班, ...

  8. TEXT 6 Travelling with baggage

    TEXT 6 Travelling with baggage 背着行囊去旅行 Feb 16th 2006 From The Economist print edition (1)FEW modern ...

  9. css 设置元素背景为透明

    要设置某一元素的背景为透明,在 chrome .firefox.opera 下是这样的: rgba 中的最后一个参数 0.4 就是想要的透明度,范围在0-1之间. 在 ie 中一般是这样的: filt ...

  10. JSP通过表格显示数据库的信息

    [step one] 1-1 建立数据库 在jsp中,我们使用的是mysql数据库,对于此数据的优缺点本篇不予以讲述,首先建立news数据库,其数据库中表的信息为: eg:< id :1 ; n ...