diff --git a/Exercise1.cpp b/Exercise1.cpp new file mode 100644 index 00000000..545fefcc --- /dev/null +++ b/Exercise1.cpp @@ -0,0 +1,39 @@ +// Problem - Pascal Triangle +// Time Complexity : O(n^2) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + +// Explaination +// 1. We initialize the result 2d array with 1 element our base condition +// 2. We go through each row and if we have our at first or last element we just +// add 1 +// 3. Otherwise we add previous_row above_col value and previous_row above_col - +// 1 value + +#include +using namespace std; + +class Solution { +public: + vector> generate(int numRows) { + vector> res = {{1}}; + if (numRows == 1) + return res; + for (int i = 1; i < numRows; i++) { + vector temp; + for (int j = 0; j <= i; j++) { + // base cond + if (j == 0 || j == i) { + temp.push_back(1); + } else { + // logic + temp.push_back(res[i - 1][j] + res[i - 1][j - 1]); + } + } + res.push_back(temp); + } + + return res; + } +}; diff --git a/Exercise2.cpp b/Exercise2.cpp new file mode 100644 index 00000000..5393c3d9 --- /dev/null +++ b/Exercise2.cpp @@ -0,0 +1,41 @@ +// Problem - K-diff pairs in an Array +// Time Complexity : O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + +// Explaination +// 1. We first sort the array so that we can use two pinters to navigate +// 2. We treat like a two sum problem skip duplicates and not using the same +// index, and make the pointer forward based on current value < k or > k +// 3. In the end we return the count + +#include +using namespace std; + +class Solution { +public: + int findPairs(vector &nums, int k) { + sort(nums.begin(), nums.end()); + int n = (int)nums.size(); + int count = 0; + int i = 0; + int j = 0; + + while (i < n && j < n) { + if (i == j || nums[j] - nums[i] < k) + j++; + else if (nums[j] - nums[i] > k) + i++; + else { + i++; + j++; + count++; + while (i < n && nums[i] == nums[i - 1]) + i++; + } + } + + return count; + } +};