Tuesday, September 8, 2020

LeetCode [410] Split Array Largest Sum

 410. Split Array Largest Sum

Hard

Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.

Write an algorithm to minimize the largest sum among these m subarrays.

 

Example 1:

Input: nums = [7,2,5,10,8], m = 2
Output: 18
Explanation:
There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and [10,8],
where the largest sum among the two subarrays is only 18.

Example 2:

Input: nums = [1,2,3,4,5], m = 2
Output: 9

Example 3:

Input: nums = [1,4,4], m = 3
Output: 4

 

Constraints:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] <= 106
  • 1 <= m <= min(50, nums.length)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
    public int splitArray(int[] nums, int m) {
        long l = 0, r = 0;
        for(long n : nums)
        {
            l = Math.max(l, n);
            r += n;
        }
        while(l<r)
        {
            long mid = l+(r-l)/2;
            if(valid(nums, mid, m))
            {
                r = mid;
            }else{
                l = mid+1;
            }
        }
        
        //r is always valid because 1) it is valid to start with 2) it is always valid on each step
        //upon exit, l==r because while(l<r). l=3, r=4, mid = 3 ==> l=mid+1=4==r
        return (int)r;
    }

    //return true if min-max <= target
    boolean valid(int[] nums, long target, int m)
    {
        int count = 0;
        long total = 0;
        for(long n:nums)
        {
            if(total+n<=target){
                total += n;
            }else{
                count++;
                if(count>m) return false;
                total = n;
            }
        }
        if(total>0) count++;
        return count<=m;
    }
}

LeetCode [417] Pacific Atlantic Water Flow

417. Pacific Atlantic Water Flow
Medium

Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.

Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.

Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.

Note:

  1. The order of returned grid coordinates does not matter.
  2. Both m and n are less than 150.

 

Example:

Given the following 5x5 matrix:

  Pacific ~   ~   ~   ~   ~ 
       ~  1   2   2   3  (5) *
       ~  3   2   3  (4) (4) *
       ~  2   4  (5)  3   1  *
       ~ (6) (7)  1   4   5  *
       ~ (5)  1   1   2   4  *
          *   *   *   *   * Atlantic

Return:

[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
class Solution {
    int[][] dir = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
    public List<List<Integer>> pacificAtlantic(int[][] matrix) {
        List<List<Integer>> ret = new ArrayList<>();
        if(matrix == null) return ret;
        int m = matrix.length;
        if(m==0) return ret;
        int n = matrix[0].length;
        if(n==0) return ret;

        Queue<int[]> queueP = new LinkedList<>();
        Queue<int[]> queueA = new LinkedList<>();
        boolean[][] pacific = new boolean[m][n];
        boolean[][] atlantic = new boolean[m][n];

        for(int i=0; i<m; ++i)
        {
            queueP.offer(new int[]{i, 0});
            queueA.offer(new int[]{i, n-1});
            pacific[i][0] = true;
            atlantic[i][n-1] = true;
        }

        for(int j=0; j<n; ++j)
        {
            queueP.offer(new int[]{0, j});
            queueA.offer(new int[]{m-1, j});
            pacific[0][j] = true;
            atlantic[m-1][j] = true;
        }

        bfs(pacific, queueP, matrix);
        bfs(atlantic, queueA, matrix);

        for(int i=0; i<m; ++i)
        {
            for(int j=0; j<n; ++j)
            {
                if(pacific[i][j] && atlantic[i][j])
                {
                    ret.add(Arrays.asList(new Integer[] {i, j}));
                }
            }
        }

        return ret;
    }

    void bfs(boolean[][] visited, Queue<int[]> que, int[][] matrix)
    {
        int m = matrix.length, n = matrix[0].length;
        while(!que.isEmpty())
        {
            int[] cor = que.poll();
            for(int[] d : dir)
            {
                int x = cor[0] + d[0];
                int y = cor[1] + d[1];
                if(x>=0 && x<m && y>=0 && y<n && !visited[x][y] && matrix[cor[0]][cor[1]]<=matrix[x][y])
                {
                    visited[x][y] = true;
                    que.offer(new int[]{x, y});
                }
            }
        }
    }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class Solution {
    int[][] dir = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
    public List<List<Integer>> pacificAtlantic(int[][] matrix) {
        List<List<Integer>> ret = new ArrayList<>();
        if(matrix == null) return ret;
        int m = matrix.length;
        if(m==0) return ret;
        int n = matrix[0].length;
        if(n==0) return ret;

        Queue<int[]> queueP = new LinkedList<>();
        Queue<int[]> queueA = new LinkedList<>();
        boolean[][] pacific = new boolean[m][n];
        boolean[][] atlantic = new boolean[m][n];

        for(int i=0; i<m; ++i)
        {
            queueP.offer(new int[]{i, 0});
            queueA.offer(new int[]{i, n-1});
            pacific[i][0] = true;
            atlantic[i][n-1] = true;
        }

        for(int j=0; j<n; ++j)
        {
            queueP.offer(new int[]{0, j});
            queueA.offer(new int[]{m-1, j});
            pacific[0][j] = true;
            atlantic[m-1][j] = true;
        }

        bfs(pacific, queueP, matrix);
        bfs(atlantic, queueA, matrix);

        for(int i=0; i<m; ++i)
        {
            for(int j=0; j<n; ++j)
            {
                if(pacific[i][j] && atlantic[i][j])
                {
                    ret.add(Arrays.asList(new Integer[] {i, j}));
                }
            }
        }

        return ret;
    }

    void bfs(boolean[][] visited, Queue<int[]> que, int[][] matrix)
    {
        int m = matrix.length, n = matrix[0].length;
        while(!que.isEmpty())
        {
            int[] cor = que.poll();
            for(int[] d : dir)
            {
                int x = cor[0] + d[0];
                int y = cor[1] + d[1];
                if(x>=0 && x<m && y>=0 && y<n && !visited[x][y] && matrix[cor[0]][cor[1]]<=matrix[x][y])
                {
                    visited[x][y] = true;
                    que.offer(new int[]{x, y});
                }
            }
        }
    }
}

LeetCode [430] Flatten a Multilevel Doubly Linked List

 430. Flatten a Multilevel Doubly Linked List

Medium

You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.

Flatten the list so that all the nodes appear in a single-level, doubly linked list. You are given the head of the first level of the list.

 

Example 1:

Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Output: [1,2,3,7,8,11,12,9,10,4,5,6]
Explanation:

The multilevel linked list in the input is as follows:



After flattening the multilevel linked list it becomes:


Example 2:

Input: head = [1,2,null,3]
Output: [1,3,2]
Explanation:

The input multilevel linked list is as follows:

  1---2---NULL
  |
  3---NULL

Example 3:

Input: head = []
Output: []

 

How multilevel linked list is represented in test case:

We use the multilevel linked list from Example 1 above:

 1---2---3---4---5---6--NULL
         |
         7---8---9---10--NULL
             |
             11--12--NULL

The serialization of each level is as follows:

[1,2,3,4,5,6,null]
[7,8,9,10,null]
[11,12,null]

To serialize all levels together we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:

[1,2,3,4,5,6,null]
[null,null,7,8,9,10,null]
[null,11,12,null]

Merging the serialization of each level and removing trailing nulls we obtain:

[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]

 

Constraints:

  • Number of Nodes will not exceed 1000.
  • 1 <= Node.val <= 10^5
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
// Definition for a Node.
class Node {
    public int val;
    public Node prev;
    public Node next;
    public Node child;
};
*/

class Solution {
    public Node flatten(Node head) {
        Node p = head;
        if(p==null) return null;
        
        while(p != null){
            if(p.child==null){
                p = p.next;
            }else{
                Node n = p.next;
                Node c = p.child;
                Node t = c; //tail of child
                while(t.next != null) t = t.next;   
                
                t.next = n;
                if(n!=null) n.prev = t;
                p.next = c;
                c.prev = p;
                p.child = null;
            }
        }
        return head;
    }
}

LeetCode [443] String Compression

 443. String Compression

Easy

Given an array of characters, compress it in-place.

The length after compression must always be smaller than or equal to the original array.

Every element of the array should be a character (not int) of length 1.

After you are done modifying the input array in-place, return the new length of the array.

 

Follow up:
Could you solve it using only O(1) extra space?

 

Example 1:

Input:
["a","a","b","b","c","c","c"]

Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]

Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".

 

Example 2:

Input:
["a"]

Output:
Return 1, and the first 1 characters of the input array should be: ["a"]

Explanation:
Nothing is replaced.

 

Example 3:

Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]

Output:
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].

Explanation:
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
Notice each digit has it's own entry in the array.

 

Constraints:

  • 1 <= chars.length <= 2000
  • chars[i].length == 1
  • chars[i] is a lower-case English letter, upper-case English letter, digit or a symbol.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public int compress(char[] chars) {
        int n = chars.length;
        int ret = 0;
        int i = 0;
        while(i<n){
            int j = i;
            while(j<n && chars[i]==chars[j]) j++;
            int count = j-i;
            chars[ret++] = chars[i];
            if(count>1){
                for(char c : Integer.toString(count).toCharArray()){
                    chars[ret++] = c;
                }
            }
            i = j;
        }
        return ret;
    }
}

LeetCode [444] Sequence Reconstruction

 444. Sequence Reconstruction

Medium

Check whether the original sequence org can be uniquely reconstructed from the sequences in seqs. The org sequence is a permutation of the integers from 1 to n, with 1 ≤ n ≤ 104. Reconstruction means building a shortest common supersequence of the sequences in seqs (i.e., a shortest sequence so that all sequences in seqs are subsequences of it). Determine whether there is only one sequence that can be reconstructed from seqs and it is the org sequence.

 

Example 1:

Input: org = [1,2,3], seqs = [[1,2],[1,3]]
Output: false
Explanation: [1,2,3] is not the only one sequence that can be reconstructed, because [1,3,2] is also a valid sequence that can be reconstructed.

Example 2:

Input: org = [1,2,3], seqs = [[1,2]]
Output: false
Explanation: The reconstructed sequence can only be [1,2].

Example 3:

Input: org = [1,2,3], seqs = [[1,2],[1,3],[2,3]]
Output: true
Explanation: The sequences [1,2], [1,3], and [2,3] can uniquely reconstruct the original sequence [1,2,3].

Example 4:

Input: org = [4,1,5,2,6,3], seqs = [[5,2,6,3],[4,1,5,2]]
Output: true

 

Constraints:

  • 1 <= n <= 10^4
  • org is a permutation of {1,2,...,n}.
  • 1 <= segs[i].length <= 10^5
  • seqs[i][j] fits in a 32-bit signed integer.

 

UPDATE (2017/1/8):
The seqs parameter had been changed to a list of list of strings (instead of a 2d array of strings). Please reload the code definition to get the latest changes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
    public boolean sequenceReconstruction(int[] org, List<List<Integer>> seqs) {
        Map<Integer, Set<Integer>> links = new HashMap<>();
        Map<Integer, Integer> degrees = new HashMap<>();

        for(List<Integer> s : seqs){
            for(int i = 0; i<s.size(); ++i){
                degrees.computeIfAbsent(s.get(i), k -> 0);
                links.computeIfAbsent(s.get(i), k -> new HashSet<>());
                if(i<s.size()-1){
                    degrees.computeIfAbsent(s.get(i+1), k -> 0);
                    if(!links.get(s.get(i)).contains(s.get(i+1))){
                        links.get(s.get(i)).add(s.get(i+1));
                        degrees.compute(s.get(i+1), (k,v) -> v=v+1);
                    }
                }
            }
        }
        if(links.size()!=org.length) return false;

        Queue<Integer> que = new LinkedList<>();
        for(Map.Entry<Integer, Integer> e : degrees.entrySet()){
            if(e.getValue()==0) que.offer(e.getKey());
        }

        int index = 0;
        while(!que.isEmpty()){
            if(que.size()>1) return false;
            int top = que.poll();
            if(index==org.length || top!=org[index++]) return false;
            for(int next : links.get(top)){
                degrees.compute(next, (k,v)->v=v-1);
                if(degrees.get(next)==0) que.offer(next);
            }
        }

        return index == org.length;
    }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
    public boolean sequenceReconstruction(int[] org, List<List<Integer>> seqs) {
        if(seqs == null || seqs.size() == 0) return false;
        int orgLen = org.length;
        int[] idx = new int[orgLen + 1];
        boolean[] pairs = new boolean[orgLen];//true: (org[i]->org[i+1]) exists
        
        for(int i = 0; i < orgLen; i++) idx[org[i]] = i;
        
        for(List<Integer> seq : seqs){
            for(int i = 0; i < seq.size(); i++){
                if(seq.get(i) > orgLen || seq.get(i) <= 0) return false;
                if(i>0){
                    int a = seq.get(i-1), b = seq.get(i);
                    if(idx[a]>=idx[b]) return false;
                    if(idx[a]+1==idx[b]) pairs[idx[a]] = true;
                }
            }
        }
        
        for(int i = 0; i < orgLen - 1; i++){
            if(!pairs[i]) return false;
        }
        
        return true;
    }
}