Press "Enter" to skip to content

Posts published in September 2018

花花酱 LeetCode 10. Regular Expression Matching

Problem

Given an input string (s) and a pattern (p), implement regular expression matching with support forĀ '.'Ā andĀ '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover theĀ entireĀ input string (not partial).

Note:

  • sĀ could be empty and contains only lowercase lettersĀ a-z.
  • pĀ could be empty and contains only lowercase lettersĀ a-z, and characters likeĀ .Ā orĀ *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation:Ā '*' means zero or more of the precedengĀ element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

Input:
s = "ab"
p = ".*"
Output: true
Explanation:Ā ".*" means "zero or more (*) of any character (.)".

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation:Ā c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

Solution 1: Recursion

Time complexity: O((|s| + |p|) * 2 ^Ā (|s| + |p|))

Space complexity: O(|s| + |p|)

C++

花花酱 LeetCode 907. Sum of Subarray Minimums

Problem

Given an array of integersĀ A, find the sum ofĀ min(B), whereĀ BĀ ranges overĀ every (contiguous) subarray ofĀ A.

Since the answer may be large,Ā return the answer moduloĀ 10^9 + 7.

Example 1:

Input: [3,1,2,4]
Output: 17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. 
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.Ā  Sum is 17.

Note:

  1. 1 <= A.length <= 30000
  2. 1 <= A[i] <= 30000

Idea

  1. order matters, unlikeĀ čŠ±čŠ±é…± LeetCode 898. Bitwise ORs of Subarrays we can not sort the numbers in this problem.
    1. e.g. sumSubarrayMins([3, 1, 2, 4]) !=sumSubarrayMins([1, 2, 3, 4]) since the first one will not have a subarray of [3,4].
  2. For A[i], assuming there are L numbers that are greater than A[i] in range A[0] ~ A[i – 1], and there are R numbers that are greater or equal than A[i] in the range of A[i+1] ~ A[n – 1]. Thus A[i] will be the min of (L + 1) * (R + 1) subsequences.
    1. e.g. A =Ā [3,1,2,4], A[1] = 1, L = 1, R = 2, there are (1 + 1) * (2 + 1) = 6 subsequences are 1 is the min number. [3,1], [3,1,2], [3,1,2,4], [1], [1,2], [1,2,4]

Solution 1: Brute Force

Time complexity: O(n^2)

Space complexity: O(1)

C++

Java

Python3 (TLE)

Solution2 : Monotonic Stack

Time complexity: O(n)

Space complexity: O(n)

We can use a monotonic stack to compute left[i] and right[i] similar toĀ čŠ±čŠ±é…± LeetCode 901. Online Stock Span

C++

Java

Python3

Python3 V2

花花酱 LeetCode 905. Sort Array By Parity

Problem

Given an arrayĀ AĀ of non-negative integers, return an array consisting of all the even elements ofĀ A, followed by all the odd elements ofĀ A.

You may return any answer array that satisfies this condition.

Example 1:

Note:

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

Solution 1: Split Odd/Even

Time complexity: O(n)

Space complexity: O(n)

C++

Solution 2: Stable sort by key % 2

Time complexity: O(nlogn)

Space complexity: O(1) in-place

C++

花花酱 LeetCode 904. Fruit Into Baskets

Problem

In a row of trees, theĀ i-th treeĀ producesĀ fruit with typeĀ tree[i].

YouĀ start at any treeĀ of your choice, then repeatedly perform the following steps:

  1. Add one piece of fruit from this tree to your baskets.Ā  If you cannot, stop.
  2. Move to the next tree to the right of the current tree.Ā  If there is no tree to the right, stop.

Note that you do not have any choice after the initial choice of starting tree:Ā you must perform step 1, then step 2, then back to step 1, then step 2, and so on until you stop.

You have two baskets, and each basket can carry any quantity of fruit, but you want each basket to only carry one type of fruit each.

What is the total amount of fruit you can collect with this procedure?

Example 1:

Input: [1,2,1]
Output: 3
Explanation: We can collect [1,2,1].

Example 2:

Input: [0,1,2,2]
Output: 3
Explanation: We can collect [1,2,2].
If we started at the first tree, we would only collect [0, 1].

Example 3:

Input: [1,2,3,2,2]
Output: 4
Explanation: We can collect [2,3,2,2].
If we started at the first tree, we would only collect [1, 2].

Example 4:

Input: [3,3,3,1,2,1,1,2,3,3,4]
Output: 5
Explanation: We can collect [1,2,1,1,2].
If we started at the first tree or the eighth tree, we would only collect 4 fruits.

Note:

  1. 1 <= tree.length <= 40000
  2. 0 <= tree[i] < tree.length

Solution: Hashtable + Sliding window

Time complexity: O(n)

Space complexity: O(1)

Keep track of the last index of each element. If a third type of fruit comes in, the new window starts after the fruit with smaller last index. Otherwise extend the current window.

[1 3 1 3 1 1] 4 1 4 … <- org window, 3 has a smaller last index than 1.

1 3 1 3 [1 1 4] 1 4 … <- new window

C++

花花酱 LeetCode 901. Online Stock Span

Problem

Write a class StockSpanner which collects daily price quotes for some stock, and returns the span of that stock’s price for the current day.

The span of the stock’s price today is defined as the maximum number of consecutive days (starting from today and going backwards) for which the price of the stock was less than or equal to today’s price.

For example, if the price of a stock over the next 7 days were [100, 80, 60, 70, 60, 75, 85], then the stock spans would be [1, 1, 1, 2, 1, 4, 6].

Example 1:

Input: ["StockSpanner","next","next","next","next","next","next","next"], [[],[100],[80],[60],[70],[60],[75],[85]]
Output: [null,1,1,1,2,1,4,6]
Explanation: 
First, S = StockSpanner() is initialized.  Then:
S.next(100) is called and returns 1,
S.next(80) is called and returns 1,
S.next(60) is called and returns 1,
S.next(70) is called and returns 2,
S.next(60) is called and returns 1,
S.next(75) is called and returns 4,
S.next(85) is called and returns 6.

Note that (for example) S.next(75) returned 4, because the last 4 prices
(including today's price of 75) were less than or equal to today's price.

Note:

  1. Calls to StockSpanner.next(int price) will have 1 <= price <= 10^5.
  2. There will be at most 10000 calls to StockSpanner.next per test case.
  3. There will be at most 150000 calls to StockSpanner.next across all test cases.
  4. The total time limit for this problem has been reduced by 75% for C++, and 50% for all other languages.

 

Solution 1: Brute Force (TLE)

Time complexity: O(n) per next call

Space complexity: O(n)

Solution 2: DP

dp[i] := span of prices[i]

j = i – 1
while j >= 0 and prices[i] >= prices[j]: j -= dp[j]
dp[i] = i – j

C++

Solution 3: Monotonic Stack

Maintain a monotonic stack whose element are pairs of <price, span>, sorted by price from high to low.

When a new price comes in

  1. If it’s less than top price, add a new pair (price, 1) to the stack, return 1
  2. If it’s greater than top element, collapse the stack and accumulate the span until the top price is higher than the new price. return the total span

e.g. prices: 10, 6, 5, 4, 3, 7

after 3, the stack looks [(10,1), (6,1), (5,1), (4,1), (3, 1)],

when 7 arrives, [(10,1), (6,1), (5,1), (4,1), (3, 1), (7, 4 + 1)] = [(10, 1), (7, 5)]

Time complexity: O(1) amortized, each element will be pushed on to stack once, and pop at most once.

Space complexity: O(n), in the worst case, the prices is in descending order.

C++

Java

Python3

Related Problems