LeetCode 57 - Insert Interval


Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].

遍历已有vector,如果当前interval小于newinterval,插入当前;如果当前interval大于newInterval,则插入newInterval及当前;如果两者重叠,merge以后插入新的interval。
实现中之所以重新new了一个vector来存放结果的原因,是不愿意破坏传入参数。
在原有的vector上面直接修改的话,唯一的区别就是,一旦发现当前interval大于newInterval,就应该return了。
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
        ArrayList<Interval> result = new ArrayList<Interval>();
        // No interval in the list
        if (intervals == null || intervals.size() == 0) {
            result.add(newInterval);
            return result;
        }
        boolean added = false;      // Indicate whether "newInterval" has been added
        // Traverse the (sorted) intervals and merge intervals
        // overlapping with "newInterval" if needed
        for (Interval interval : intervals) {
            if (interval.end < newInterval.start)   // Non-overlapping intervals ahead "newInterval"
                result.add(interval);
            else if (interval.start > newInterval.end) {    // Non-overlapping intervals behind "newInterval"
                // If "newInterval" has not been added, add it before the current interval
                if (!added) {
                    result.add(newInterval);
                    added = true;
                }
                result.add(interval);
            } else {    // Overlapping intervals
                // Merge the current interval with "newInterval", and reflect it in "newInterval"
                newInterval.start = Math.min(newInterval.start, interval.start);
                newInterval.end = Math.max(newInterval.end, interval.end);
            }
        }
        // In case "newInterval" has not been added in the loop
        if (!added)
            result.add(newInterval);
        return result;
    }
Code from http://www.programcreek.com/2012/12/leetcode-insert-interval/
     public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
 
        ArrayList<Interval> result = new ArrayList<Interval>();
 
        for(Interval interval: intervals){
            if(interval.end < newInterval.start){
                result.add(interval);
            }else if(interval.start > newInterval.end){
                result.add(newInterval);
                newInterval = interval;        
            }else if(interval.end >= newInterval.start || interval.start <= newInterval.end){
                newInterval = new Interval(Math.min(interval.start, newInterval.start), Math.max(newInterval.end, interval.end));
            }
        }
 
        result.add(newInterval); 
 
        return result;
    }

https://leetcode.com/problems/insert-interval/discuss/21602/Short-and-straight-forward-Java-solution
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
    List<Interval> result = new LinkedList<>();
    int i = 0;
    // add all the intervals ending before newInterval starts
    while (i < intervals.size() && intervals.get(i).end < newInterval.start)
        result.add(intervals.get(i++));
    // merge all overlapping intervals to one considering newInterval
    while (i < intervals.size() && intervals.get(i).start <= newInterval.end) {
        newInterval = new Interval( // we could mutate newInterval here also
                Math.min(newInterval.start, intervals.get(i).start),
                Math.max(newInterval.end, intervals.get(i).end));
        i++;
    }
    result.add(newInterval); // add the union of intervals we got
    // add all the rest
    while (i < intervals.size()) result.add(intervals.get(i++)); 
    return result;
}
Instead of using new operator, why not just do newInterval.start = . This will make sure you're not creating new objects in a while loop. Great solution though! :)

No need to use additional memory. In place solution with little bit change.
public List<Interval> insert(List<Interval> intervals, Interval newInterval) {``
        int i=0;
        while(i<intervals.size() && intervals.get(i).end<newInterval.start) i++;
        while(i<intervals.size() && intervals.get(i).start<=newInterval.end){
            newInterval = new Interval(Math.min(intervals.get(i).start, newInterval.start), Math.max(intervals.get(i).end, newInterval.end));
            intervals.remove(i);
        }
        intervals.add(i,newInterval);
        return intervals;
}

Extended: In case we want to add the interval in place:
    public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
        if(intervals==null||newInterval==null) {
            return intervals;
        }
        
        if(intervals.size()==0) {
            intervals.add(newInterval);
            return intervals;
        }
        
        ListIterator<Interval> it = intervals.listIterator();
        while(it.hasNext()) {
            Interval tmpInterval = it.next();
            if(newInterval.end<tmpInterval.start) {
                it.previous();
                it.add(newInterval);
                return intervals;
            } else {
                if(tmpInterval.end<newInterval.start) {
                    continue;
                } else {
                    newInterval.start = Math.min(tmpInterval.start, newInterval.start);
                    newInterval.end   = Math.max(tmpInterval.end, newInterval.end);
                    it.remove();
                }
            }
        }
        intervals.add(newInterval);
        return intervals;
    }

出题的人,添加了一个附属条件,这些interval是在一个圆环上。比如当环是[1, 255]时,如果两个Interval分别是[1,234], [222, 4], Merge最后的结果是[1,4]。这个条件完全是个干扰,因为如果真的在逻辑中考虑环的话,非常麻烦,而且在环上做循环合并的话,无法判断何时该终止循环。当时我的解法就是,如果第一个是跨越0点的话(比如[234,7]),把它拆分成两个interval([234, 255],[1,7]), 然后把[1,7]插到队头,[234,255]插到队尾。 从[1,7]开始往后合并,合并完成后,再检查对头及队尾,需要的话,再合并一次即可。

X.
https://leetcode.com/discuss/93980/java-binary-search-solution-beats-with-clear-explaination
The idea is using binary search to find the position that the newInterval to be inserted.
Since the original intervals are sorted and disjoint, we can apply binary search to find the insertion index of newInterval.start (by interval.start), and to find the insertion index of newInterval.end(by interval.end), 【see LeeCode problem #35】. Then remove the overlapped elements of the list and merge the newInterval with boundary elements on two sides.
Complexity: O(log n) in time (in fact, depending on the implement of the access method list.get(i) and of list.subList(int, int).clear()); O(1) in space.
public List<Interval> insert(List<Interval> intervals, Interval newInterval) { /** * Since the original list is sorted and all intervals are disjoint, * apply binary search to find the insertion index for the new * interval. [LC35] * * 1. Find insIdx=the insertion index of new.start, i.e., the first * index i such that list.get(i).start>=new.start. * * 2. Find nxtIdx=the insertion index of new.end, i.e., the first * index i such that list.get(i).end>=new.end. * * 3. Remove all elements of the list with indices insIdx<=i<nxtIdx. * * 4. Merge new with list.get(insIdx-1) or list.get(nxtIdx) or both. */ int n = intervals.size(); if (n == 0) { intervals.add(newInterval); return intervals; } int low = 0, high = n - 1, mid = 0; int temp, target = newInterval.start; while (low <= high) { mid = (low + high) / 2; temp = intervals.get(mid).start; if (temp == target) break; if (temp < target) low = mid + 1; else high = mid - 1; } // insIdx = the index where new interval to be inserted int insIdx = (low <= high) ? mid : low; Interval pre = (insIdx == 0) ? null : intervals.get(insIdx - 1); // 0<=insIdx<=n, pre=[insIdx-1], pre.start<new.start low = insIdx; high = n - 1; target = newInterval.end; while (low <= high) { mid = (low + high) / 2; temp = intervals.get(mid).end; if (temp == target) break; if (temp < target) low = mid + 1; else high = mid - 1; } // nxtIdx= the next index after the inserted new interval int nxtIdx = (low <= high) ? mid : low; Interval nxt = (nxtIdx == n) ? null : intervals.get(nxtIdx); // insIdx<=nxtIdx<=n, nxt=[nxtIdx], nxt.end>=new.end // [0]...[insIdx-1] <--> [insIdx]...[nxtIdx-1][nxtIdx]...[n] intervals.subList(insIdx, nxtIdx).clear(); // check whether newInterval can be merged with pre or nxt boolean isMerged = false, isMerged2 = false; if (insIdx > 0 && pre.end >= newInterval.start) { pre.end = Math.max(pre.end, newInterval.end); isMerged = true; } if (nxtIdx < n && newInterval.end >= nxt.start) { nxt.start = Math.min(nxt.start, newInterval.start); isMerged2 = isMerged; isMerged = true; } if (!isMerged) { intervals.add(insIdx, newInterval); return intervals; } // merged with pre or nxt or both, deal with the both case if (isMerged2 && pre.end >= nxt.start) { nxt.start = pre.start; // pre.start < new.start, nxt.start; intervals.remove(insIdx - 1); // remove pre } return intervals; }

https://leetcode.com/discuss/42018/7-lines-3-easy-solutions


def insert(self, intervals, newInterval):
    s, e = newInterval.start, newInterval.end
    left, right = [], []
    for i in intervals:
        if i.end < s:
            left += i,
        elif i.start > e:
            right += i,
        else:
            s = min(s, i.start)
            e = max(e, i.end)
    return left + [Interval(s, e)] + right
X. Not Good
https://leetcode.com/discuss/33249/short-java-code
Set newInterval to null
public List<Interval> insert(List<Interval> intervals, Interval newInterval) { List<Interval> result = new ArrayList<Interval>(); for (Interval i : intervals) { if (newInterval == null || i.end < newInterval.start) result.add(i); else if (i.start > newInterval.end) { result.add(newInterval); result.add(i); newInterval = null; } else { newInterval.start = Math.min(newInterval.start, i.start); newInterval.end = Math.max(newInterval.end, i.end); } } if (newInterval != null) result.add(newInterval); return result; }
Read full article from LeetCode - Insert Interval | Darren's Blog

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts