Amazon OA (9.22 to 10.13)

5,679 阅读4分钟

Leetcode OA List Link

Amazon Fresh Promotion

private static int isWinner(String[][] codeList,String[] shoppingCart){
    //check zero length...
    if(codeList == null || codeList.length == 0)
        return 1;
    if(shoppingCart == null || shoppingCart.length == 0)
        return 0;
    int i=0,j=0;
    for(int k=0;k<shoppingCart.length;k++) {
        //when match success
        if(codeList[i][j].equals(shoppingCart[k]) || codeList[i][j].equals("anything")) {
            j++;
            if(j == codeList[i].length) {
                i++;
                j=0;
            }
            if(i == codeList.length)
                return 1;
        }else {
            //when match failed, k and j both go back.
            k-=j;
            j=0;
        }
    }
    return 0;
}

Amazon Music Pairs/ LC 1010

6// We can simplify this problem as a Two Sum problem. For each time[i], we want to find how many time[j]
// (0<= j < i) can satisfy the requirement (time[i] + time[j]) % 60 = (time[i] % 60 + time[j] % 60) = 0.
// We can use an array/map to store the number of each time[j]%60. I use array beacause time[j]%60 <= 59
// which is small, the "get" operation should be faster considered the hash collisions of map.
// Time: O(N) -> traverse time array once
// Space: 60 -> arr size 60, will be a constant if time is large enough
public int numPairsDivisibleBy60(int[] time) {
      int result = 0;
      int[] remainder = new int[60];
      for (int i = 0; i < time.length; i++) {
          result += remainder[(60 - time[i] % 60) % 60];
          remainder[time[i] % 60]++;
      }
      return result;
  }

Items in Containers/ AOC

1次
Traverse the array two times, use dp[N][3] to store numbers of item up to now, nearest left/ right gate
Each interval we need O(1) time to find result

Largest Item Association

和岛屿问题很像,建一个Map<Integer, List<Integer>>存下来所有的对应关系,用bfs queue去找到所有相关的item
用set来记录所有遍历过的数字

Turnstile/ AOC

Use two queue to store exiting person and entering person

Five Star Sellers/ AOC

6次
Use max PriorityQueue/Heap to store the index by product[0] + 1 / prodcut[1] + 1 - product[0] / product[1]
O((N + R) * logN) -> time where R is the result of function, O(N) -> heap
* Need to take care about about int / double type problem ,整数相除分子需要变double*

Beta Testing/similar to LC 1335 🆕

But not all same.

// We use dynamic programming to solve this problem, dp[i][k] means the min difficulty we use to
// finish i jobs in k days. The transition is dp[j][k - 1] (min difficulty we use to finish i jobs
// in k - 1 days) + max of jobDifficulty[j + 1 to i] which is the difficulty of i-th day.
public int minDifficulty(int[] jobDifficulty, int d) {
    if (jobDifficulty.length < d) return -1;
    int[][] dp = new int[jobDifficulty.length + 1][d + 1];
    dp[0][0] = 0;
    int maxTemp = 0;
    for (int i = 1; i <= jobDifficulty.length; i++) {
        maxTemp = Math.max(maxTemp, jobDifficulty[i - 1]);
        dp[i][1] = maxTemp;
    }

    for (int i = 1; i <= jobDifficulty.length; i++) {
        for (int k = 2; k <= d; k++) {
            int max = 0;
            int min = Integer.MAX_VALUE;
            for (int j = i - 1; j >= k - 1; j--) {
                max = Math.max(max, jobDifficulty[j]);
                min = Math.min(min, dp[j][k - 1] + max);
            }
            dp[i][k] = min;
        }
    }
    return dp[jobDifficulty.length][d];
}

Top K Frequently Mentioned Keywords

2次
We use max-heap to store the result, if their frequency are same, we use compareTo()
We use a set1 to store all keywords to achieve O(1) get time.
For each string we use another set2, word in set1 and not in set2 will be put in map.

Transaction Logs/ AOC

  • Collections.sort(list, (a, b) -> Integer.valueOf(b) - Integer.valueOf(a));
5
1p3a:TreeMap 挺方便,注意“088“ 和 ”88“ 不一样,88 在 088 前面。
1p3a:corner cases很多,test cases不好过的。所以别掉以轻心。
public String[] processLogFile(String[] logs, int threshold) {
    Map<String, Integer> map = new HashMap<>();
    List<String> list = new ArrayList<>();
    for (String log : logs) {
        String[] words = log.split(" ");
        map.put(words[0], map.getOrDefault(words[0], 0) + 1);
        if (!words[0].equals(words[1])) {
            map.put(words[1], map.getOrDefault(words[1], 0) + 1);
        }
    }
    for (String key : map.keySet()) {
        if (map.get(key) >= threshold) {
            list.add(key);
        }
    }
    Collections.sort(list, (a, b) -> Integer.valueOf(b) - Integer.valueOf(a));
    String[] result = new String[list.size()];
    for (int i = 0; i < list.size(); i++) {
        result[i] = list.get(i);
    }
    return result;
}

Substrings of Size K with K-1 Distinct Chars

Use a map and two pointer as a sliding window to determine if current string from left to right
is a length K string with K - 1 distinct char by map.size()
- substring(left, right + 1)
public static List<String> solve(String S, int k) {
    List<String> list = new ArrayList<>();
    if (S == null || S.length() < k || k == 0) return list;
    Map<Character, Integer> map = new HashMap<>();
    Set<String> result = new HashSet<>();
    int left = 0;
    for (int right = 0; right < S.length(); right++) {
        char currChar = S.charAt(right);
        map.put(currChar, map.getOrDefault(currChar, 0) + 1);
        if (right - left == k - 1) { // reach the target length
            if (map.size() == k - 1) { // k character with k - 1 distinct
                result.add(S.substring(left, right + 1));
            }
            if (map.get(S.charAt(left)) == 1) {
                map.remove(S.charAt(left));
            } else {
                map.put(S.charAt(left), map.get(S.charAt(left)) - 1);
            }
            left++;
        }
    }
    for (String target: result) {
        list.add(target);
    }
    return list;
}

Videos Link

Number of Islands

Use DFS to reach all place connected to current '1'

Most Common Word/ LC 819

// 1. Store lowercased paragraph into string array
// 2. Traverse array and count numbers of each word into HashMap
// 3. Traverse banned array and remove ban words from HashMap
// 4. Traverse HashMap to find Max
String[] words = paragraph.toLowerCase().split("\\W+");
Map<String, Integer> map = new HashMap<>();
int max = 0;
String res = "";
for (String word : words) {
    map.put(word, map.getOrDefault(word, 0) + 1);
}
for (String word : banned) {
    map.remove(word);
}
for (String Key : map.keySet()) {
    if (map.get(Key) > max) {
        max = map.get(Key);
        res = Key;
    }
}
return res;

Distance Between Nodes in BST

3

K Closest Points to Origin/ LC 973

Map heap, keep K -> O(2 * K) space, O(NlogN) time
2
1p3a:用O(n^3) 也过了,刷题网讨论区有个烙印朋友的给的java答案有个小错误, count初始用的0,应该用个max_value,大家注意一下。

OneCode

Secret Fruit List

Find Related Products

Shopping Patterns

8
// First we use a Map<Integer, List<Integer>> to store a number and all number connected to it
// Build a String set to store all edges
// For each number that list.size() > 2, we go through the list and find if any couple are in set

1p3a:找trio,O(VE),对每个点做2层BFS/或者找它的两个邻居是否相连。所以是worst caseO(VE)。注意去重以及只有有两个及以上邻居的点,才需要做BFS。所以其实worst case基本达不到。
1p3a:本质就是一个graph找trio。做法就是每个node查一遍看看和他链接的两个node是不是也互相链接。

一亩三分地

1.

第二题 给了两个array,以及一个target number。 
从两个array里分别选一个,sum小于等于target number,return最接近target的组合。2 sum的变形吧。

1

2. Friend Circle/ Gifting Group/ LC 547

6
// Traverse 0 to N people, for ith persone, if it is already connected by previous people -> we skip this person
// else we use a queue to find all direct/ indirect friends 

// Time Complexity : O(N * N) -> The complete matrix of size n^2 is traversed.
// Space Complexity : O(N) -> one set and one queue with size N
public int findCircleNum(int[][] M) {
    HashSet<Integer> set = new HashSet<>();
    int result = 0;
    for (int i = 0; i < M.length; i++) {
        if (set.contains(i)) continue;
        result++;
        Queue<Integer> queue = new LinkedList<>();
        queue.add(i);
        set.add(i);
        while (queue.size() > 0) {
            int row = queue.poll();
            for (int j = 0; j < M.length; j++) {
                if (M[row][j] == 1 && !set.contains(j)) {
                    queue.add(j);
                    set.add(j);
                }
            }
        }
    }
    return result;
}

3. Minimum Difficulty of a Job Schedule/ LC 1335

6

4. Utility checks/ Autoscale Policy

LC Link

6
(利口搜Twitter, autoscale policy,连测试用例都是同一个就改了名字)
1p3a: 给一个初始的computing instances数量,和一个array代表每一秒CPU的utilization,比如[4,25,17,87]代表1-4秒的utilization分别是4%, 25%, 17% 和87%, 然后给出对不同utilization对应的computing instances的处理方法: 0 - 25要把computing instances减半;25 - 60什么都不干,60以上要加倍,但是加倍后的总量不能超过2 * 10 ^ 8, 最后返回最终的computing instances的数量
1 当碰到不需要改变computing instances的时候,要直接跳过接下来的10s
2 奇数减半取ceil
1p3a: 似乎偏简单,但被提到corner cases很多,test cases不好过的。所以别掉以轻心。

LeetCode原题

Partition Labels/ LC 763

Reorder Data in Log Files/ LC 937 9月25

LC: 340, 200,1381 / 414, 1339, 1381