Skip to content
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
39 changes: 39 additions & 0 deletions Exercise1.cpp
Original file line number Diff line number Diff line change
@@ -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 <bits/stdc++.h>
using namespace std;

class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res = {{1}};
if (numRows == 1)
return res;
for (int i = 1; i < numRows; i++) {
vector<int> 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;
}
};
41 changes: 41 additions & 0 deletions Exercise2.cpp
Original file line number Diff line number Diff line change
@@ -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 <bits/stdc++.h>
using namespace std;

class Solution {
public:
int findPairs(vector<int> &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;
}
};