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
27 changes: 27 additions & 0 deletions problem1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/* Pascal's Triangle */

// Time Complexity : O(n^2), where n = numRows
// Space Complexity : O(1) auxiliary space, O(n^2) is the size of the output
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no


// Your code here along with comments explaining your approach
// The first and second rows will always be [1] and [1,1] respectively
// For each row, we need to calculate the elements between index 0 and index i-1, which is given by the formula: row[j] = triangle[i-1][j-1] + triangle[i-1][j]
// After we fill a row, push it into the triangle matrix at the appropriate index

class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> triangle(numRows);
for(int i=0; i<numRows; i++) {
vector<int> row(i+1, 1);
for(int j=1; j<i; j++) {
row[j] = triangle[i-1][j-1] + triangle[i-1][j];
}
triangle[i] = row;
}
return triangle;
}
};
46 changes: 46 additions & 0 deletions problem2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/* K-Diff Pairs */

// Time Complexity : O(nlogn)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no


// Your code here along with comments explaining your approach
// Sort the array and then start pointer i at index 0 and pointer j at index 1
// Check the difference nums[j] - nums[i]: if the diff is too big then move i forward, else move j forward
// When we find the pair, increment ans and then increment i & j to the next unique element
// When we increment i & j to the next unique element, we might end up with i & j at the same index, so put an if condition at the start of the loop to handle this

class Solution {
public:
int findPairs(vector<int>& nums, int k) {
int n = nums.size();
if (n == 1) return 0;

sort(nums.begin(), nums.end());
int ans = 0;
int i = 0; int j = 1;

while(i < n && j < n) {
if (i == j) { // to ensure distinct indices
j++;
continue;
}
int a = nums[i];
int b = nums[j];
if(b - a == k) { // we found a pair
ans++;
while(i < n && nums[i] == a) i++; // to ensure no duplicate pairs
while(j < n && nums[j] == b) j++;
}
else if(b - a < k) { // diff is too small, increase j
j++;
} else { // diff is too big, increase i
i++;
}
}

return ans;
}
};