Skip to content

Commit

Permalink
Added some code
Browse files Browse the repository at this point in the history
  • Loading branch information
codeAbinash committed Oct 5, 2023
1 parent cde7912 commit c713a7a
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 33 deletions.
27 changes: 27 additions & 0 deletions leetcode/problems/cpp/duplicate-zeros.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// by @codeAbinash
// Time : O(n)
// Space : O(n)

#include "algorithm"
#include "vector"
using namespace std;


class Solution {
public:
void duplicateZeros(vector<int>& arr) {
int zeroCount = count(arr.begin(), arr.end(), 0);
int size = arr.size();
int newSize = size + zeroCount;
arr.resize(newSize);

int i = size - 1;
while (i >= 0) {
if (!arr[i]) zeroCount--;
if (i + zeroCount < newSize) arr[i + zeroCount] = arr[i];
if (!arr[i] && i + zeroCount + 1 < newSize) arr[i + zeroCount + 1] = arr[i];
i--;
}
arr.resize(size);
}
};
37 changes: 37 additions & 0 deletions leetcode/problems/cpp/find-duplicate-subtrees.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// by @codeAbinash
// Time : O(n^2)
// Space : O(n)

#include "vector"
#include "string"
#include "unordered_map"
using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
vector<TreeNode*> res;
unordered_map<string, int> map;
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
dfs(root);
return res;
}

string dfs(TreeNode* root) {
if (!root) return "#";
string left = dfs(root->left);
string right = dfs(root->right);
string subTree = left + "," + right + "," + to_string(root->val);
if (map[subTree] == 1) res.push_back(root);
map[subTree]++;
return subTree;
}
};
47 changes: 14 additions & 33 deletions leetcode/problems/cpp/merge-sorted-array.cpp
Original file line number Diff line number Diff line change
@@ -1,33 +1,14 @@
// by @CodeAntu
// time complexity o(m+n)
// space complexity o(1)



void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = m - 1;
int j = n - 1;
int k = m + n - 1;

while (i >= 0 && j >= 0)
{
if (nums1[i] > nums2[j])
{
nums1[k] = nums1[i];
i--;
} else {
nums1[k] = nums2[j];
j--;
}
k--;
}
if (i < 0)
{
while (j >= 0)
{
nums1[k] = nums2[j];
j--;
k--;
}
}
}
#include "vector"
using namespace std;

class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int i = m - 1, j = n - 1, k = m + n - 1;
while (i >= 0 && j >= 0) {
if (nums1[i] > nums2[j]) nums1[k--] = nums1[i--];
else nums1[k--] = nums2[j--];
}
while (j >= 0) nums1[k--] = nums2[j--];
}
};

0 comments on commit c713a7a

Please sign in to comment.