25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Solutions to Chapter 10 | Ma<strong>the</strong>matical<br />

10 6 Given a two dimensional graph with points on it, find a line which passes <strong>the</strong> most<br />

number of points<br />

SOLUTION<br />

1 9 3<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Concepts and Algorithms<br />

pg 68<br />

If we draw a line between every two points, we can check to see which line is <strong>the</strong> most common<br />

A brute force approach would be to simply iterate through each line segment (formed<br />

by pairs of points) and count how many points fall on it This would take O(N^3) time<br />

Before we discuss if we can do better, let’s figure out how we can represent a line A line can<br />

be represented in (at least) two different ways: (1) as a pairing of points or (2) as a slope and<br />

a y-intercept<br />

Because our line is infinite, <strong>the</strong> slope and y-intercept approach seems more appropriate<br />

The slope and y-intercept approach has an additional advantage: every line segment on <strong>the</strong><br />

same greater line will have identical slopes and y-intercepts<br />

Let’s re-think our solution We have a bunch of line segments, represented as a slope and<br />

y-intercept, and we want to find <strong>the</strong> most common slope and y-intercept How can we find<br />

<strong>the</strong> most common one?<br />

This is really no different than <strong>the</strong> old “find <strong>the</strong> most common number in a list of numbers”<br />

problem We just iterate through <strong>the</strong> lines segments and use a hash table to count <strong>the</strong> number<br />

of times we’ve seen each line<br />

1 public static Line findBestLine(GraphPoint[] points) {<br />

2 Line bestLine = null;<br />

3 HashMap line_count = new HashMap();<br />

4 for (int i = 0; i < points.length; i++) {<br />

5 for (int j = i + 1; j < points.length; j++) {<br />

6 Line line = new Line(points[i], points[j]);<br />

7 if (!line_count.containsKey(line)) {<br />

8 line_count.put(line, 0);<br />

9 }<br />

10 line_count.put(line, line_count.get(line) + 1);<br />

11 if (bestLine == null ||<br />

12 line_count.get(line) > line_count.get(bestLine)) {<br />

13 bestLine = line;<br />

14 }<br />

15 }<br />

16 }<br />

17 return bestLine;<br />

18 }<br />

19<br />

20 public class Line {<br />

21 private static double epsilon = .0001;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!