Press "Enter" to skip to content

Posts published in December 2018

花花酱 LeetCode 936. Stamping The Sequence

Problem

You want to form aĀ targetĀ string ofĀ lowercase letters.

At the beginning, your sequence isĀ target.lengthĀ '?'Ā marks.Ā  You also have aĀ stampĀ of lowercase letters.

On each turn, you may place the stamp over the sequence, and replace every letter in the sequence with the corresponding letter from the stamp.Ā  You can make up toĀ 10 * target.lengthĀ turns.

For example, if the initial sequence isĀ “?????”, and your stamp isĀ "abc",Ā  then you may makeĀ “abc??”, “?abc?”, “??abc”Ā in the first turn.Ā  (Note that the stamp must be fully contained in the boundaries of the sequence in order to stamp.)

If the sequence is possible to stamp, then return an array ofĀ the index of the left-most letter being stamped at each turn.Ā  If the sequence is not possible to stamp, return an empty array.

For example, if the sequence isĀ “ababc”, and the stamp isĀ "abc", then we could return the answerĀ [0, 2], corresponding to the movesĀ “?????” -> “abc??” -> “ababc”.

Also, if the sequence is possible to stamp, it is guaranteed it is possible to stamp withinĀ 10 * target.lengthĀ moves.Ā  Any answers specifying more than this number of movesĀ will not be accepted.

Example 1:

Input: stamp = "abc", target = "ababc"
Output: [0,2]
([1,0,2] would also be accepted as an answer, as well as some other answers.)

Example 2:

Input: stamp = "abca", target = "aabcaca"
Output: [3,0,1]

Note:

  1. 1 <= stamp.length <= target.length <= 1000
  2. stampĀ andĀ targetĀ only contain lowercase letters.

Solution: Greedy + Reverse Simulation

Reverse the stamping process. Each time find a full or partial match. Replace the matched char to ‘?’.

Don’t forget the reverse the answer as well.

T = “ababc”, S = “abc”

T = “ab???”, index = 2

T = “?????”, index = 0

ans = [0, 2]

Time complexity: O((T – S)*S)

Space complexity: O(T)

C++

花花酱 LeetCode 952. Largest Component Size by Common Factor

Problem

Given a non-emptyĀ array of unique positive integersĀ A, consider the following graph:

  • There areĀ A.lengthĀ nodes, labelledĀ A[0]Ā toĀ A[A.length - 1];
  • There is an edge betweenĀ A[i]Ā andĀ A[j]Ā if and only ifĀ A[i]Ā andĀ A[j]Ā share a common factor greater than 1.

Return the size of the largest connected component in the graph.

Example 1:

Input: [4,6,15,35]
Output: 4

Example 2:

Input: [20,50,9,63]
Output: 2

Example 3:

Input: [2,3,6,7,4,12,21,39]
Output: 8

Note:

  1. 1 <= A.length <= 20000
  2. 1 <= A[i] <= 100000

Solution: Union Find

For each number, union itself with all its factors.

E.g. 6, union(6,2), union(6,3)

Time complexity:Ā \( O(\Sigma{sqrt(A[i])})Ā Ā \)

Space complexity: \( O(max(A)) \)

C++

Python3