0% found this document useful (0 votes)
23 views7 pages

Assignment - 2

Uploaded by

Irfan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views7 pages

Assignment - 2

Uploaded by

Irfan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Assignment – 2

Student Name: Vishal Kumar Singh UID:23BCS80020


Branch: BE- CSE Date of Completion: 13-06-2024
Faculty Name: Ms. Shefali goyal

Question 1-
Minimum Insertion Steps to Make a String Palindrome - LeetCode

CODE:
class Solution {
public:
int minInsertions(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n, 0));

for (int i = 0; i < n; ++i)


{
dp[i][i] = 1;
}

for (int i = n - 2; i >= 0; --i) {


for (int j = i + 1; j < n; ++j) {
if (s[i] == s[j]) {
dp[i][j] = 2 + dp[i + 1][j - 1];
} else {
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
}
}

return n-dp[0][n - 1];


}
};

SOLUTION:

Question 2: -
Permutations II - LeetCode

Code:
class Solution {
public:
vector<vector<int>> res;
void permute(vector<int> nums, int start){
if(start==nums.size()){
res.push_back(nums);
return;
}
for(int i=start;i<nums.size();i++){
if(i==start || nums[start]!=nums[i]){
swap(nums[start],nums[i]);
permute(nums,start+1);
}
}

}
vector<vector<int>> permuteUnique(vector<int>& nums) {
int start=0;
sort(nums.begin(), nums.end());
permute(nums,start);
return res;
}
};
SOLUTION:

Question 3: -
Group Anagrams - LeetCode

Code:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> mp;
for(auto x: strs){
string word = x;
sort(word.begin(), word.end());
mp[word].push_back(x);
}

vector<vector<string>> ans;
for(auto x: mp){
ans.push_back(x.second);
}
return ans;
}
};

Solution:

Question 4: -

Continuous Subarray Sum - LeetCode

Code:
class Solution {
public:
static bool checkSubarraySum(vector<int>& nums, int k) {
int n=nums.size();
if (n<2) return 0;
unordered_map<int, int> mod_k;
int prefix=0;
mod_k.reserve(n);
mod_k[0]=-1;
for(int i=0; i<n; i++){
prefix+=nums[i];
prefix%=k;
if (mod_k.count(prefix)){
if(i>mod_k[prefix]+1)
return 1;
}
else
mod_k[prefix]=i;
}
return 0;
}

};

auto init = []() {


ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 'c';
}();
Solution:

Question 5: -

Longest Word in Dictionary - LeetCode

Code:
class Solution {
public:
string longestWord(vector<string>& words) {
sort(words.begin(), words.end());
unordered_set<string> built;
string res;
for (string w : words) {
if (w.size() == 1 || built.count(w.substr(0, w.size() - 1))) {
res = w.size() > res.size() ? w : res;
built.insert(w);
}
}
return res;
}
};

You might also like