Skip to content

Commit 3d15503

Browse files
authored
Merge pull request #2955 from Abe0770/main
Create 2657-find-the-prefix-common-array-of-two-arrays.cpp
2 parents aa34c3c + ebc3544 commit 3d15503

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
You are given two 0-indexed integer permutations A and B of length n.
3+
A prefix common array of A and B is an array C such that C[i] is equal to the count of numbers that are present at or before the index i in both A and B.
4+
Return the prefix common array of A and B.
5+
A sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
6+
7+
Ex. Input: A = [1,3,2,4], B = [3,1,2,4]
8+
Output: [0,2,3,4]
9+
Explanation: At i = 0: no number is common, so C[0] = 0.
10+
At i = 1: 1 and 3 are common in A and B, so C[1] = 2.
11+
At i = 2: 1, 2, and 3 are common in A and B, so C[2] = 3.
12+
At i = 3: 1, 2, 3, and 4 are common in A and B, so C[3] = 4.
13+
14+
Time : O(n)
15+
Space : O(n)
16+
*/
17+
18+
class Solution {
19+
public:
20+
vector<int> findThePrefixCommonArray(vector<int>& A, vector<int>& B) {
21+
vector<int> C;
22+
vector<int> v(A.size()+1,0);
23+
int count = 0;
24+
25+
for(int i = 0; i < A.size(); ++i){
26+
if(v[A[i]] < 0)
27+
count++;
28+
++v[A[i]];
29+
30+
if(v[B[i]]>0)
31+
count++;
32+
--v[B[i]];
33+
34+
C.push_back(count);
35+
}
36+
return C;
37+
}
38+
};
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
You are given a 0-indexed string s and a dictionary of words dictionary.
3+
You have to break s into one or more non-overlapping substrings such that each substring is present in dictionary.
4+
There may be some extra characters in s which are not present in any of the substrings.
5+
6+
Return the minimum number of extra characters left over if you break up s optimally.
7+
8+
Ex. Input: s = "leetscode", dictionary = ["leet","code","leetcode"]
9+
Output: 1
10+
Explanation: We can break s in two substrings: "leet" from index 0 to 3 and "code" from index 5 to 8. There is only 1 unused character (at index 4), so we return 1.
11+
12+
Time : O(N^M) M = dictionary.size(), N = s.size()
13+
Space : O(N)
14+
*/
15+
16+
class Solution {
17+
public:
18+
int minExtraChar(string s, vector<string>& dictionary) {
19+
int n = s.size();
20+
vector<int> dp(n + 1, n);
21+
22+
dp[0] = 0;
23+
24+
for (int i = 1; i <= n; ++i) {
25+
for(int j = 0 ; j < dictionary.size() ; ++j) {
26+
int len = dictionary[j].size();
27+
if (i >= len && s.substr(i - len, len) == dictionary[j]) {
28+
dp[i] = min(dp[i], dp[i - len]);
29+
}
30+
}
31+
dp[i] = min(dp[i], dp[i - 1] + 1);
32+
}
33+
34+
return dp[n];
35+
}
36+
};

0 commit comments

Comments
 (0)