0% found this document useful (0 votes)
40 views

Godaddy

The document contains solutions to common algorithm problems in C++. It includes solutions to string compression, unique paths with obstacles, word break, longest palindromic substring, merge intervals, number of islands, perfect squares, permutations, LRU cache, minimum window substring, and finding the median of two sorted arrays. The solutions utilize techniques like dynamic programming, breadth-first search, sliding window, hashing, and sorting to optimize runtime and space complexity.

Uploaded by

garvitagg27
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)
40 views

Godaddy

The document contains solutions to common algorithm problems in C++. It includes solutions to string compression, unique paths with obstacles, word break, longest palindromic substring, merge intervals, number of islands, perfect squares, permutations, LRU cache, minimum window substring, and finding the median of two sorted arrays. The solutions utilize techniques like dynamic programming, breadth-first search, sliding window, hashing, and sorting to optimize runtime and space complexity.

Uploaded by

garvitagg27
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/ 14

String Compression

class Solution {

public:

int compress(vector<char>& chars) {

unordered_map<char, int> mp;

string str = "";

for (int i = 0; i < chars.size(); i++)

if (mp.count(chars[i]) || mp.empty())

mp[chars[i]]++;

else if (mp.size() > 0)

string temp = to_string(mp[chars[i - 1]]);

str += chars[i - 1];

if (temp.compare("1") != 0)

str += temp;

mp.clear();

mp[chars[i]] = 1;

string temp1 = to_string(mp[chars[chars.size() - 1]]);

str += chars[chars.size() - 1];

if (temp1.compare("1") != 0)

str += temp1;

for (int i = 0; i < str.length(); i++)

chars[i] = str[i];
return str.length();

};

Unique Paths II

class Solution {

public:

int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {

if (obstacleGrid.empty() || obstacleGrid[0][0] == 1) {

return 0;

int rows = obstacleGrid.size();

int cols = obstacleGrid[0].size();

vector<int> dp(cols, 0);

dp[0] = 1;

for (int r = 0; r < rows; r++) {

for (int c = 0; c < cols; c++) {

if (obstacleGrid[r][c] == 1) {

dp[c] = 0;

} else {

if (c > 0) {

dp[c] += dp[c - 1];

}
return dp[cols - 1];

};

Word Break

class Solution {

public:

bool wordBreak(string s, vector<string>& wordDict) {

int n = s.size();

//key: end index, 1-based

vector<bool> dp(n+1, false);

//empty string

dp[0] = true;

for(int end = 1; end <= n; ++end){

for(int start = 0; start < end; ++start){

//dp[start]: s[0...start-1]

if(dp[start] && find(wordDict.begin(), wordDict.end(), s.substr(start, end-start)) !=


wordDict.end()){

//s[0...end-1] can be split into s[0...start-1] and s[start...end-1]

dp[end] = true;

break;

return dp[n];

};
Longest Palindromic Substring

class Solution {

public:

int expandAroundCenter(string s, int left, int right)

int start = left, end = right;

int n = s.length();

// Expand the center.

while (start >= 0 && end < n && s[start] == s[end])

start--;

end++;

return end - start - 1;

string longestPalindrome(string s) {

int n = s.length();

if (n < 1)

return "";

int start = 0, end = 0;


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

// Longest odd length palindrome with center points as i.

int len1 = expandAroundCenter(s, i, i);

// Longest even length palindrome with center points as i and i + 1.

int len2 = expandAroundCenter(s, i, i + 1);

int len = max(len1, len2);

// Update the start and end.

if (len > end - start + 1)

start = i - (len - 1) / 2;

end = i + (len) / 2;

return s.substr(start, end - start + 1);

};

Merge Intervals

class Solution {

public:

vector<vector<int>> merge(vector<vector<int>>& intervals) {

int n = intervals.size();
// sort the intervals

sort(intervals.begin(), intervals.end());

vector<vector<int>> res;

// push the 1st interval into res

res.push_back(intervals[0]);

// max_end will store max_end value till ith

int max_end = intervals[0][1];

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

// start end end value of prev merged interval

int prev_start = res.back()[0];

int prev_end = res.back()[1];

// start and end value of current interval

int curr_start = intervals[i][0];

int curr_end = intervals[i][1];

// update the max_end

max_end = max(max_end, curr_end);


// if we found an overlapping interval

if(curr_start <= prev_end)

res.pop_back();

res.push_back({prev_start, max_end});

// if interval is not overlapping

else

res.push_back({curr_start, max_end});

return res;

};

Number of Islands

class Solution {

public:

void dfs(int row,int col,vector<vector<char>>&grid,vector<vector<int>>&vis){

int n=grid.size(),m=grid[0].size();

if(row<0||row>=n||col<0||col>=m||grid[row][col]=='0'||vis[row][col]){

return;

}
vis[row][col]=1;

vector<pair<int,int>>dir={{1,0},{0,1},{-1,0},{0,-1}};

for(auto ele:dir){

int nr=row+ele.first,nc=col+ele.second;

dfs(nr,nc,grid,vis);

int numIslands(vector<vector<char>>& grid) {

int n=grid.size();

int m=grid[0].size();

int cnt=0;

vector<vector<int>>vis(n,vector<int>(m,0));

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

for(int j=0;j<m;j++){

if(!vis[i][j]&&grid[i][j]=='1'){

cnt++;

dfs(i,j,grid,vis);

return cnt;

};

Perfect Squares

class Solution {

public:

int solve(int n)
{

vector<int> dp(n+1, INT_MAX);

dp[0] = 0;

for (int i = 1; i <= n; i++){

for (int j = 1; j*j <= n; j++){

int temp = j*j;

if (i - temp >= 0)

dp[i] = min(dp[i], 1 + dp[i - temp]);

return dp[n];

int numSquares(int n) {

return solve(n);

};

Permutations

class Solution {

public:

vector<vector<int>>v;

void solve(vector<int>&a,int idx)

if(idx >= a.size())

v.push_back(a);

return;

}
for(int i = idx; i < a.size(); i++)

swap(a[i],a[idx]);

solve(a,idx+1);

swap(a[i],a[idx]);

vector<vector<int>> permute(vector<int>& a) {

vector<int>p;

solve(a,0);

return v;

};

LRU Cache

#include <iostream>

#include <map>

class LRUCache {

public:

LRUCache(int capacity) : capacity(capacity) {

int get(int key) {

if (data.find(key) != data.end()) {

int value;

data[key] = value;

return value;

}
return -1;

void put(int key, int value) {

if (data.find(key) != data.end()) {

// If the key already exists, update its value and move it to the end (most recently used) of the
map

data.erase(key);

} else if (data.size() == capacity) {

// If the map is full, remove the least recently used key (first element) from the map

auto it = data.begin();

data.erase(it);

// Insert the new key-value pair at the end (most recently used) of the map

data[key] = value;

private:

int capacity;

map<int, int> data;

};

Minimum Window Substring

class Solution {

public:

string minWindow(string s, string t) {

if(t.size()>s.size())return "";

int n=s.size();
unordered_map<char,int>mp;

unordered_map<char,int>mp2;

for(auto it: t){

mp[it]++;

int j=0;

int i=0;

int ans=1e9;

int final_i=-1;

int final_j=-1;

while(j<n){

mp2[s[j]]++;

while( i<n && j<n && mp.find(s[i])==mp.end() ){

mp2[s[i]]--;

if(mp2[s[i]]==0)mp2.erase(s[i]);

i++;

while(i<n && mp2[s[i]]>mp[s[i]]){

mp2[s[i]]--;

i++;

bool f=0;

for(auto it: mp){

char c=it.first;

int freq=it.second;

if(mp2.find(c)==mp2.end())f=1;

else{

if(mp2[c]<mp[c])f=1;
}

if(f==0){

if(j-i+1<ans){

final_i=i;

final_j=j;

ans=min(ans,j-i+1);

j++;

if(final_i==-1 && final_j==-1)return "";

return s.substr(final_i,final_j-final_i+1);

};

Median of Two Sorted Arrays

class Solution {

public:

double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {

vector<int> mergedArr;

for (int i = 0; i < nums1.size() + nums2.size(); i++) {

if (i < nums1.size())

mergedArr.push_back(nums1[i]);

else

mergedArr.push_back(nums2[i - nums1.size()]);

}
sort(mergedArr.begin(), mergedArr.end());

double ans;

if ((nums1.size() + nums2.size()) % 2 != 0) {

ans = mergedArr[(nums1.size() + nums2.size()) / 2];

else {

ans = (mergedArr[(nums1.size() + nums2.size()) / 2] +

mergedArr[((nums1.size() + nums2.size()) / 2) - 1]) / 2.0;

return ans;

};

You might also like