diff --git a/problem1.cpp b/problem1.cpp new file mode 100644 index 00000000..22d67a9d --- /dev/null +++ b/problem1.cpp @@ -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> generate(int numRows) { + vector> triangle(numRows); + for(int i=0; i row(i+1, 1); + for(int j=1; j& 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; + } +}; \ No newline at end of file