Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
interval_list_intersections [2020/08/19 19:36] paul created |
interval_list_intersections [2020/08/19 20:58] (current) |
||
---|---|---|---|
Line 3: | Line 3: | ||
I dedicated a whole page to this problem. | I dedicated a whole page to this problem. | ||
- | This was asked at of me at an interview and I flubbed it. I attempted this problem a month after the interview and I still didn't fully get it, and made numerous mistakes which I want to analyze. | + | This was asked at of me at an interview and I flubbed it. I attempted this |
+ | problem a month after the interview and I still didn't fully get it, and made | ||
+ | numerous mistakes which I want to analyze. | ||
+ | |||
+ | Here is the algorithm I came up with: | ||
+ | |||
+ | {{: | ||
+ | |||
+ | Here is the code that I wrote: | ||
<code cpp> | <code cpp> | ||
- | class Solution | + | vector< |
- | public: | + | |
| | ||
- | vector< | + | |
+ | |||
+ | | ||
+ | | ||
+ | | ||
+ | |||
+ | while(pa < A.size() || pb < B.size() ) | ||
+ | { // get next interval | ||
+ | // deal with pointers going out of bounds | ||
+ | if ( pa >= A.size() | ||
+ | else if ( pb >= B.size() | ||
+ | else if ( A[pa][0] <= B[pb][0] ) { cur = A[pa++]; | ||
+ | else { cur = B[pb++]; | ||
| | ||
- | int pa = 0, pb = 0; | + | |
+ | | ||
+ | int max_start | ||
| | ||
- | vector< | + | |
- | vector< | + | { |
- | | + | out.push_back({max_start, |
+ | } | ||
+ | last = cur; | ||
+ | } | ||
+ | return out; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Here's a review of the original algorithm with the mistakes I made. | ||
+ | |||
+ | {{: | ||
+ | |||
+ | Algorithm: | ||
+ | |||
+ | {{: | ||
+ | |||
+ | Code: | ||
+ | <code cpp> | ||
+ | vector< | ||
+ | |||
+ | int pa = 0, pb = 0; | ||
+ | | ||
+ | |||
+ | // if any pointer goes out of bounds, we are done checking! | ||
+ | while( pa < A.size() && pb < B.size() ) | ||
+ | | ||
+ | int min_end | ||
+ | int max_start = max(A[pa][0], | ||
| | ||
- | | + | if(max_start |
- | { // get next interval | + | { |
- | // deal with pointers going out of bounds | + | out.push_back({max_start, |
- | | + | |
- | else if ( pb >= B.size() | + | |
- | else if ( A[pa][0] | + | |
- | | + | |
- | | + | |
- | // check if next intersects with last | + | |
- | int min_end | + | |
- | int max_start = max(last[0], | + | |
- | + | ||
- | if(min_end >= max_start) | + | |
- | { | + | |
- | | + | |
- | } | + | |
- | last = cur; | + | |
} | } | ||
- | | + | |
+ | // push forward the pointer to the element with the smallest end | ||
+ | if(A[pa][1] < B[pb][1]) | ||
+ | pa++; | ||
+ | else | ||
+ | pb++; | ||
} | } | ||
- | }; | + | return out; |
+ | } | ||
</ | </ | ||
+ |