Wednesday, September 30, 2020

LeetCode [1029] Two City Scheduling

 1029. Two City Scheduling

Medium

A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.

Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.

 

Example 1:

Input: costs = [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation: 
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.

The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.

Example 2:

Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
Output: 1859

Example 3:

Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
Output: 3086

 

Constraints:

  • 2n == costs.length
  • 2 <= costs.length <= 100
  • costs.length is even.
  • 1 <= aCosti, bCosti <= 1000
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    public int twoCitySchedCost(int[][] costs) {
        int n = costs.length;
        int[] diff = new int[n];
        int minCost = 0, index = 0;
        for(int[] cost : costs){
            diff[index++] = cost[1] - cost[0];
            minCost += cost[0];
        }
        Arrays.sort(diff);
        for(int i = 0; i < n/2; i++){
            minCost += diff[i];
        }
        return minCost;
    }
}

LeetCode [609] Find Duplicate File in System

 609. Find Duplicate File in System

Medium

Given a list of directory info including directory path, and all the files with contents in this directory, you need to find out all the groups of duplicate files in the file system in terms of their paths.

A group of duplicate files consists of at least two files that have exactly the same content.

A single directory info string in the input list has the following format:

"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"

It means there are n files (f1.txtf2.txt ... fn.txt with content f1_contentf2_content ... fn_content, respectively) in directory root/d1/d2/.../dm. Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.

The output is a list of group of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:

"directory_path/file_name.txt"

Example 1:

Input:
["root/a 1.txt(abcd) 2.txt(efgh)", "root/c 3.txt(abcd)", "root/c/d 4.txt(efgh)", "root 4.txt(efgh)"]
Output:  
[["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]

 

Note:

  1. No order is required for the final output.
  2. You may assume the directory name, file name and file content only has letters and digits, and the length of file content is in the range of [1,50].
  3. The number of files given is in the range of [1,20000].
  4. You may assume no files or directories share the same name in the same directory.
  5. You may assume each given directory info represents a unique directory. Directory path and file info are separated by a single blank space.

 

Follow-up beyond contest:
  1. Imagine you are given a real file system, how will you search files? DFS or BFS?
  2. If the file content is very large (GB level), how will you modify your solution?
  3. If you can only read the file by 1kb each time, how will you modify your solution?
  4. What is the time complexity of your modified solution? What is the most time-consuming part and memory consuming part of it? How to optimize?
  5. How to make sure the duplicated files you find are not false positive?
 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
class Solution {
    Map<String, List<String>> duplicate = new HashMap<>();
    public List<List<String>> findDuplicate(String[] paths) {
        for(String path:paths) getPath(path);
        List<List<String>> list = new ArrayList<>();
        for(List<String> l : duplicate.values()) if(l.size()>1) list.add(l);
        return list;
    }

    void getPath(String str){
        int n = str.length();
        int endOfPath = str.indexOf(' ', 0);
        if(endOfPath==-1) return;//no file in the dir

        String path = str.substring(0, endOfPath);
        
        //get all files
        int start = endOfPath+1;
        while(start<n){
            int endOfFile = str.indexOf(' ', start);
            if(endOfFile<0) endOfFile = n;//dealing with last file;
            String file = str.substring(start, endOfFile);
            getFiles(path, file);
            start = endOfFile+1;
        }
    }

    void getFiles(String path, String file){
        int index1 = file.indexOf('(');
        int index2 = file.indexOf(')');
        String fileName = file.substring(0, index1);
        String fileContent = file.substring(index1+1, index2);
        duplicate.computeIfAbsent(fileContent, k->new ArrayList<>()).add(path+"/"+fileName);
    }
}

LeetCode [1292] Maximum Side Length of a Square with Sum Less than or Equal to Threshold

 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold

Medium

Given a m x n matrix mat and an integer threshold. Return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.

 

Example 1:

Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
Output: 2
Explanation: The maximum side length of square with sum less than 4 is 2 as shown.

Example 2:

Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1
Output: 0

Example 3:

Input: mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6
Output: 3

Example 4:

Input: mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184
Output: 2

 

Constraints:

  • 1 <= m, n <= 300
  • m == mat.length
  • n == mat[i].length
  • 0 <= mat[i][j] <= 10000
  • 0 <= threshold <= 10^5
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public int maxSideLength(int[][] mat, int threshold) {
        int n = mat.length;
        int m = mat[0].length;
        int[][] sums = new int[n + 1][m + 1];
        int max = 0;        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                sums[i + 1][j + 1] = sums[i + 1][j] + sums[i][j + 1] - sums[i][j] + mat[i][j];
                if (i - max >= 0 && j - max >= 0 && 
                    sums[i + 1][j + 1] - sums[i - max][j + 1] - sums[i + 1][j - max] + sums[i - max][j - max] <= threshold
                   ) {
                    max += 1;
                }
            }
        }
        return max;    
    }
}

LeetCode [845] Longest Mountain in Array

 845. Longest Mountain in Array

Medium

Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:

  • B.length >= 3
  • There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]

(Note that B could be any subarray of A, including the entire array A.)

Given an array A of integers, return the length of the longest mountain

Return 0 if there is no mountain.

Example 1:

Input: [2,1,4,7,3,2,5]
Output: 5
Explanation: The largest mountain is [1,4,7,3,2] which has length 5.

Example 2:

Input: [2,2,2]
Output: 0
Explanation: There is no mountain.

Note:

  1. 0 <= A.length <= 10000
  2. 0 <= A[i] <= 10000

Follow up:

  • Can you solve it using only one pass?
  • Can you solve it in O(1) space?
 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
class Solution {
    public int longestMountain(int[] A) {
        int n = A.length;
        int[] dp1 = new int[n];
        int[] dp2 = new int[n];
        for(int i=1; i<n; ++i){
            if(A[i]>A[i-1]){
                dp1[i] = dp1[i-1]+1;
            }
        }
        for(int i=n-2; i>=0; --i){
            if(A[i]>A[i+1]){
                dp2[i] = dp2[i+1]+1;
            }
        }
        
        int r = 0;
        for(int i=1; i<n-1; ++i){
            if(dp1[i]>0 && dp2[i]>0){
                int t = dp1[i] + dp2[i] + 1;
                r = Math.max(r, t);
            }
        }
        return r;
    }
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
    public int longestMountain(int[] A) {
        int res = 0, up = 0, down = 0;
        for (int i = 1; i < A.length; ++i) {
            if (down > 0 && A[i - 1] < A[i] || A[i - 1] == A[i]) up = down = 0;
            if (A[i - 1] < A[i]) up++;
            if (A[i - 1] > A[i]) down++;
            if (up > 0 && down > 0 && up + down + 1 > res) res = up + down + 1;
        }
        return res;
    }
}

LeetCode [420] Strong Password Checker

 420. Strong Password Checker

Hard

A password is considered strong if below conditions are all met:

  1. It has at least 6 characters and at most 20 characters.
  2. It must contain at least one lowercase letter, at least one uppercase letter, and at least one digit.
  3. It must NOT contain three repeating characters in a row ("...aaa..." is weak, but "...aa...a..." is strong, assuming other conditions are met).

Write a function strongPasswordChecker(s), that takes a string s as input, and return the MINIMUM change required to make s a strong password. If s is already strong, return 0.

Insertion, deletion or replace of any one character are all considered as one change.

 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
class Solution {
    public int strongPasswordChecker(String s) {
        int res = 0, a = 1, A = 1, d = 1;
        char[] carr = s.toCharArray();
        int[] arr = new int[carr.length];
            
        for (int i = 0; i < arr.length;) {
            if (Character.isLowerCase(carr[i])) a = 0;
            if (Character.isUpperCase(carr[i])) A = 0;
            if (Character.isDigit(carr[i])) d = 0;
                
            int j = i;
            while (i < carr.length && carr[i] == carr[j]) i++;
            arr[j] = i - j;
        }
        //missing lowerCase + upperCase + digit    
        int total_missing = (a + A + d);
    
        if (arr.length < 6) {
            //at most 1 segment with >=3 repeating chars, which can be resolve whiling filling total_missing char
            res += total_missing + Math.max(0, 6 - (arr.length + total_missing));    
        } else {
            int over_len = Math.max(arr.length - 20, 0), left_over = 0;
            res += over_len;
                
            //while removing over_len, we can fix 3-repeating segments
            //deal with xxx and xxxx by remove 1 and 2 from them
            for (int k = 1; k < 3; k++) {
                for (int i = 0; i < arr.length && over_len > 0; i++) {
                    if (arr[i] < 3 || arr[i] % 3 != (k - 1)) continue;
                    arr[i] -= Math.min(over_len, k);
                    over_len -= k;
                }
            }
                
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] >= 3 && over_len > 0) {
                    int need = arr[i] - 2;
                    arr[i] -= over_len;
                    over_len -= need;
                }
                    
                //left 3-repeated segments
                //xxxxxxxyyy -> xx1xx1xyyZ
                if (arr[i] >= 3) left_over += arr[i] / 3;
            }
                
            res += Math.max(total_missing, left_over);
        }
            
        return res;
    }
    }