Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created new directory - CPP with codes related to arrays, binary tree and dynamic programming #37

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions CPP/Array/All pair whose sum is k.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
link: https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/1

https://www.geeksforgeeks.org/count-pairs-with-given-sum/
*/


// ----------------------------------------------------------------------------------------------------------------------- //
// using hashing (aka unordered_map)
int getPairsCount(int arr[], int n, int sum)
{
unordered_map<int, int> m;

// Store counts of all elements in map m
for (int i = 0; i < n; i++)
m[arr[i]]++;

int twice_count = 0;

// iterate through each element and increment the
// count (Notice that every pair is counted twice)
for (int i = 0; i < n; i++) {
twice_count += m[sum - arr[i]];

// if (arr[i], arr[i]) pair satisfies the condition,
// then we need to ensure that the count is
// decreased by one such that the (arr[i], arr[i])
// pair is not considered
if (sum - arr[i] == arr[i])
twice_count--;
}

// return the half of twice_count
return twice_count / 2;
}



// ----------------------------------------------------------------------------------------------------------------------- //
// naive solution (TLE)
// TC: O(n^2)
int getPairsCount(int arr[], int n, int sum)
{
int count = 0; // Initialize result

// Consider all possible pairs and check their sums
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] + arr[j] == sum)
count++;

return count;
}
46 changes: 46 additions & 0 deletions CPP/Array/Array subset of anothe array.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
link: https://practice.geeksforgeeks.org/problems/array-subset-of-another-array2317/1#
*/


// ----------------------------------------------------------------------------------------------------------------------- //
// TC: O(N)
// SC: O(N)
string isSubset(int a1[], int a2[], int n, int m) {
unordered_set<int> s;
for (int i = 0;i < n;i++) {
s.insert(a1[i]);
}
for (int i = 0;i < m;i++) {
if (s.find(a2[i]) == s.end()) return "No";
}
return "Yes";
}



// ----------------------------------------------------------------------------------------------------------------------- //
// similar solution.
string isSubset(int a1[], int a2[], int n, int m) {

unordered_map<int, int> um, um2;

for (int i = 0; i < n; i++) {
um[a1[i]]++;
}
for (int i = 0; i < m; i++) {
um2[a2[i]]++;
}

int count = 0;
for (auto it = um2.begin(); it != um2.end(); it++) {
if (um[it->first] >= it->second) {
count++;
}
}

if (count == m)
return "Yes";
else
return "No";
}
20 changes: 20 additions & 0 deletions CPP/Array/Best time to buy stock.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

also refer to 26_sell_...twice.cpp
*/


// ----------------------------------------------------------------------------------------------------------------------- //
int maxProfit(vector<int>& prices) {
int n = prices.size();
int local = 0, global = 0;
for (int i = 1;i < n;i++) {
/*
if the loss is going negative then make it 0 either continue with the profit as higher as possible.
*/
local = max(0, local += prices[i] - prices[i - 1]);
global = max(local, global);
}
return global;
}
18 changes: 18 additions & 0 deletions CPP/Array/Choclate distribution problem.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
link: https://practice.geeksforgeeks.org/problems/chocolate-distribution-problem3825/1
*/


// ----------------------------------------------------------------------------------------------------------------------- //
long long findMinDiff(vector<long long> a, long long n, long long m) {
// sorted so that we can different window(sub-array) of size m.
sort(a.begin(), a.end());

long long ans = a[m - 1] - a[0]; // took first window from 0 to m-1.

// now we iterate every window(sub-array) and check for the max-min from that range.
for (int i = 1;i < n - m + 1;i++) {
ans = min(a[i + m - 1] - a[i], ans);
}
return ans;
}
54 changes: 54 additions & 0 deletions CPP/Array/Common element in 3 sorted arrays.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
link: https://practice.geeksforgeeks.org/problems/common-elements1132/1
*/


// ----------------------------------------------------------------------------------------------------------------------- //
vector <int> commonElements(int a[], int b[], int c[], int n1, int n2, int n3)
{
set<int> ans;
int i = 0, j = 0, k = 0;
while (i < n1 and j < n2 and k < n3) {
if (a[i] == b[j] && a[i] == c[k]) {
ans.insert(a[i]);
i++;
j++;
k++;
}
else if (a[i] < b[j] || a[i] < c[k]) i++;
else if (b[j] < a[i] || b[j] < c[k]) j++;
else if (c[k] < b[j] || c[k] < a[i]) k++;
}
vector<int> nn;
for (ele : ans) {
nn.push_back(ele);
}
return nn;
}



// ----------------------------------------------------------------------------------------------------------------------- //
// alternate solution (improved)
vector <int> commonElements(int A[], int B[], int C[], int n1, int n2, int n3)
{
int i = 0, j = 0, k = 0;

vector <int> res;
int last = INT_MIN;
while (i < n1 and j < n2 and k < n3)
{
if (A[i] == B[j] and A[i] == C[k] and A[i] != last)
{
res.push_back(A[i]);
last = A[i];
i++;
j++;
k++;
}
else if (min({ A[i], B[j], C[k] }) == A[i]) i++;
else if (min({ A[i], B[j], C[k] }) == B[j]) j++;
else k++;
}
return res;
}
108 changes: 108 additions & 0 deletions CPP/Array/Count inversion.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
link: https://practice.geeksforgeeks.org/problems/inversion-of-array-1587115620/1#

video (recommended to save time): https://youtu.be/kQ1mJlwW-c0

condition here is convertion counts if (arr[i]>arr[j] && i<j) <-- keep this in mind everytime
*/



// ----------------------------------------------------------------------------------------------------------------------- //
/*
Time Complexity: O(n^2),
Two nested loops are needed to traverse the array from start to end, so the Time complexity is O(n^2)
Space Complexity:O(1), No extra space is required.
*/
long long int inversionCount(long long arr[], long long N)
{
// Your Code Here
long long ans = 0LL;
for (int i = 0;i < N;i++) {
for (int j = i + 1;j < N;j++) {
if (arr[j] < arr[i]) ans++;
}
}
return ans;
}



// ----------------------------------------------------------------------------------------------------------------------- //
/*
Time Complexity: O(n log n),
The algorithm used is divide and conquer, So in each level,
one full array traversal is needed, and there are log n levels,
so the time complexity is O(n log n).
Space Complexity: O(n), Temporary array.

just trace it and it will be easy to understand
*/


// This func merges two sorted arrays and returns inversion count in the arrays.
int merge(int arr[], int temp[], int left, int mid, int right) {
int i, j, k;
int inv_count = 0;

i = left; /* i is index for left subarray*/
j = mid; /* j is index for right subarray*/
k = left; /* k is index for resultant merged subarray*/
while ((i <= mid - 1) && (j <= right)) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
}
else {
temp[k++] = arr[j++];

/* this is tricky -- see above explanation/diagram for merge()*/
inv_count += mid - i;
}
}

/* Copy the remaining elements of left subarray
(if there are any) to temp*/
while (i <= mid - 1)
temp[k++] = arr[i++];

/* Copy the remaining elements of right subarray
(if there are any) to temp*/
while (j <= right)
temp[k++] = arr[j++];

/*Copy back the merged elements to original array*/
for (i = left; i <= right; i++)
arr[i] = temp[i];

return inv_count;
}


/* An auxiliary recursive function that sorts the input array and returns the number of inversions in the array. */
int _mergeSort(int arr[], int temp[], int left, int right)
{
int mid, inv_count = 0;
if (right > left) {
/* Divide the array into two parts and call _mergeSortAndCountInv() for each of the parts */
mid = (right + left) / 2;

/* Inversion count will be sum of inversions in left-part, right-part and number of inversions in merging */
inv_count += _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid + 1, right);

/*Merge the two parts*/
inv_count += merge(arr, temp, left, mid + 1, right);
}
return inv_count;
}

// Driver code
int main()
{
int arr[] = { 1, 20, 6, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int temp[n];
int ans = _mergeSort(arr, temp, 0, n - 1);
cout << " Number of inversions are " << ans;
return 0;
}
15 changes: 15 additions & 0 deletions CPP/Array/Cyclically rotate by 1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*
link: https://practice.geeksforgeeks.org/problems/cyclically-rotate-an-array-by-one2614/1
*/


// ----------------------------------------------------------------------------------------------------------------------- //
void rotate(int arr[], int n)
{
int temp = arr[n - 1];

for (int i = n - 1;i > 0;i--) {
arr[i] = arr[i - 1];
}
arr[0] = temp;
}
19 changes: 19 additions & 0 deletions CPP/Array/Kadane's algorithms.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
link: https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1
*/


// ----------------------------------------------------------------------------------------------------------------------- //
int maxSubarraySum(int arr[], int n) {
int dp[n];
dp[0] = max(INT_MIN, arr[0]);
int omax = dp[0];

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

dp[i] = max(arr[i] + dp[i - 1], arr[i]);

omax = max(dp[i], omax);
}
return omax;
}
10 changes: 10 additions & 0 deletions CPP/Array/Kth max min.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
link: https://practice.geeksforgeeks.org/problems/kth-smallest-element5635/1

sol: https://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/
or
refer heap/5th_kth....cpp

*/


19 changes: 19 additions & 0 deletions CPP/Array/Largest continous sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
link: https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1

kadane's algorithm
*/


// ----------------------------------------------------------------------------------------------------------------------- //
int maxSubarraySum(int arr[], int n) {
int dp[n];

dp[0] = max(0, arr[0]);
int omax = dp[0];
for (int i = 1;i < n;i++) {
dp[i] = max(dp[i - 1] + arr[i], arr[i]);
omax = max(dp[i], omax);
}
return omax;
}
Loading