Google

683. K Empty Slots

Given an array flowers consists of number from 1 to N. Each number in the array represents the place where the flower will open in that day. Given an integer k, you need to output in which day there exists two flowers in the status of blooming, and also the number of flowers between them is k and these flowers are not blooming.

1 O(nlogn)

  • Use the TreeSet to record the already open place

  • TreeSet add, delete, search O(logn)

  • return the first one match requirement

public int kEmptySlots(int[] flowers, int k) {
    TreeSet<Integer> active = new TreeSet();
    int day = 0;
    for (int flower: flowers) {
        day++;
        active.add(flower);
        Integer lower = active.lower(flower)
        Integer higher = active.higher(flower);
        if (lower != null && flower - lower - 1 == k ||
                higher != null && higher - flower - 1 == k)
            return day;
    }
    return -1;
}

2 O(n)

  • A position array, pos[x] = i means the flower x blooms at i day

  • fix left and right pointer, check if we can find an array [left, 1, 2,..., k, right] is valids

889. Construct Binary Tree from Preorder and Postorder Traversal

Return any binary tree that matches the given preorder and postorder traversals.

Example

Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1] Output: [1,2,3,4,5,6,7]

  • find the length of left tree and use it split the left tree and right tree

  • Preorder and postorder left tree length are the same, and pre[1] the head of left tree, use is to find the last position in postorder

280 Wiggle Sort

Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....

324 Wiggle Sort II

Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....

  • Copy the array and sort it, the number smaller than mid should put in odd slots; others should put in even slots.

475 Heaters

you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters.

Example: Input: [1,2,3,4],[1,4] Output: 1

656 Coin Path

Given an array(index start from 1), B is the step you can jump from index i. Return the path indexes starting from 1 to last index in array.

  • A next[] array to record the indexes

  • Statement: dp[i] is the min jumping cost starting from index i to end of array.

  • Func: dp[i] = min(A[i]+dp[i+B]) B <- 1:B

  • Ans: Loop the next[], if index == -1, then return empty list

399. Evaluate Division

Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.

  • Time: O(q+ q*E), q is the number of queries, E is the connecting edges. The best case of E is 1, worst is length of equations

    • Space: O(q)

524. Longest Word in Dictionary through Deleting

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

  • Implement a isSubsequence method

792. Number of Matching Subsequences

Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.

1 Brute Force

  • Time: O(words.len*S.len)

  • Space: O(1)

2 Variant Trie

  • Class node to record the word and current index

  • Time: O(S.len)

  • Space: O(words.len)

  • loop list 注意 concurrency, new ArraList

835. Image Overlap

Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)

We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images.

What is the largest possible overlap?

  • Count the moving vector from image A to image B

  • Time O(n^4)

328. Odd Even Linked List

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

844. Backspace String Compare

Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.

857. Minimum Cost to Hire K Workers

There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i].

Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules:

  1. Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.

  2. Every worker in the paid group must be paid at least their minimum wage expectation.

Return the least amount of money needed to form a paid group satisfying the above conditions.

843. Guess the Word

We are given a word list of unique words, each word is 6 letters long, and one word in this list is chosen as secret.

You may call master.guess(word) to guess a word. You can not guess the word more than 10 times. The test case has 100 words in wordlist

  • Strategy: find a word 有最大的可猜測族群, 利用guess API縮減wordlist

863. All Nodes Distance K in Binary Tree

We are given a binary tree (with root node root), a target node, and an integer value K.

Return a list of the values of all nodes that have a distance K from the target node.

  • Node分兩種,從target往上跟往下

  • findTarget(), 返回target跟node之間的距離

    1. node is null

    2. target is node

    3. dfs計算node.left, node.right

    4. 分別根據距離addNode(), 返回距離

858. Mirror Reflection

There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.

The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.

Return the number of the receptor that the ray meets first.

  • 想像box向上延伸m次,laser反射n次

Explain

855. Exam Room

In an exam room, there are N seats in a single row, numbered 0, 1, 2, ..., N-1.

When a student enters the room, they must sit in the seat that maximizes the distance to the closest person

  • Need a dynamic sorted array, use TreeSet

  • 比較dist分三部分

    1. array head to first seat

    2. seat betweens

    3. last seat to array tail

853. Car Fleet

N cars is array. Each car i has a constant speed speed[i] and initial position position[i]

A car can never pass another car ahead of it, if car A catch up car B, they are assumed to have the same position.

Return how many car fleets arrive target

850. Rectangle Area II

We are given a list of (axis-aligned) rectangles. Each rectangle[i] = [x1, y1, x2, y2] , where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the ith rectangle.

Find the total area covered by all rectangles in the plane. Since the answer may be too large, return it modulo 10^9 + 7.

  • 記錄每一個rectangle 在y軸上in & out的event, 並且sort by y dimention

  • Use sweep line to count x distance, multiple y diff

  • Put 'in' event in active lit, move 'out' event

846. Hand of Straights

Alice has a hand of cards, given as an array of integers.

Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.

Return true if and only if she can.

  • Use a TreeMap to record the frequency and continuous of number

845. Longest Mountain in Array

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]

return the longest len of mountain

833. Find And Replace in String

  • The indexes is not sorted order, use a map to store the string index and array index

  • StringBuilder starts to update from rear, it doesn't affect the subString

818. Race Car

Your car starts at position 0 and speed +1 on an infinite number line. (Your car can go into negative positions.)

Your car drives automatically according to a sequence of instructions A (accelerate) and R (reverse).

When you get an instruction "A", your car does the following: position += speed, speed *= 2.

When you get an instruction "R", your car does the following: if your speed is positive then speed = -1 , otherwise speed = 1. Return the shortest sequence of instructions

  • Recursion + memorization

  • DP(t): the shortest sequence to achieve target

  • 3 condition

    1. t is exact nA: n

    2. t is over 2^n-1 (nA1R): n+1+helper(left)

    3. t is reverse twice (n-1)ARmAR: (n+m+1) + helper( t - (2^(n-1)-1+2^(m)-1))

Explain

815. Bus Routes

We have a list of bus routes. Each routes[i] is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7], this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever.

We start at bus stop S (initially not on a bus), and we want to go to bus stop T. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible.

  • BFS from bust stop 2 each routes it connected

  • Prune if stop is visited

805. Split Array With Same Average

In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)

Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.

  • The avg of A and avg of B and C are the same.

  • totalSum/n = Asum/k => Asum = totalSum*k/n整除

  • 利用combinationSum, 遞回到 k=0 && remain == 0

684. Redundant Connection

Undirected Graph

  • Use union find to find cycle

685. Redundant Connection II

Directed Graph

  • 3 circumstances

    1. Only multiple parents

    2. Only cycle

    3. Both

Example:[[2,1],[3,1],[4,2],[1,4]]

312. Burst Balloons

Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] nums[i] nums[right] coins. Here left and right are adjacent indices of i. nums[-1] = nums[n] = 1

  • dp[i][j]: 第i個到第j個nums的array中, ballon burst的最大值

  • Trans: dp[i][j] = dp[i][k-1] + nums[i]nums[k]nums[j] + dp[k+1][j], i <= k <= j

  • Ans: dp[1][n]

Back 1017t. Similar RGB Color

Given the color "#ABCDEF", return a 7 character color that is most similar to #ABCDEF, and has a shorthand (that is, it can be represented as some "#XYZ")

Last updated

Was this helpful?