diff --git a/problem1.cpp b/problem1.cpp new file mode 100644 index 00000000..11ab8c3a --- /dev/null +++ b/problem1.cpp @@ -0,0 +1,29 @@ +// Time Complexity : O(n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : yes +// Three line explanation of solution in plain english + +// Your code here along with comments explaining your approach +// First, we go over the array from left to right to find the left running product +// Then we go over the array from right to left, maintaining a right running product +// The product of an array except a particular element will be the left product (existing result array) * right product + +class Solution { +public: + vector productExceptSelf(vector& nums) { + int n = nums.size(); + vector result(n); + result[0] = 1; + int leftProduct = 1; // left running product + for(int i=1; i=0; i--) { + rightProduct = rightProduct*nums[i+1]; + result[i] = result[i]*rightProduct; + } + return result; + } +}; \ No newline at end of file diff --git a/problem2.cpp b/problem2.cpp new file mode 100644 index 00000000..cc80b6a3 --- /dev/null +++ b/problem2.cpp @@ -0,0 +1,49 @@ +// Time Complexity : O(m*n) +// Space Complexity : O(1) +// Did this code successfully run on Leetcode : yes +// Three line explanation of solution in plain english + +// Your code here along with comments explaining your approach +// Start traversion from element at (0,0) +// Collect the element at each step and put it in the answer vector +// If we hit the boundary of the matrix (top most row, bottom most col, upper right element, bottom left element) change the direction + +class Solution { +public: + vector findDiagonalOrder(vector>& mat) { + int m = mat.size(); + int n = mat[0].size(); + vector ans(m*n); + bool dir = true; // up + int r=0; + int c=0; + for(int i=0; i spiralOrder(vector>& matrix) { + int m = matrix.size(); int n = matrix[0].size(); + int top = 0; int bottom = m - 1; + int left = 0; int right = n - 1; + vector result; + while(left <= right && top <= bottom) { + for(int j=left; j<=right; j++) { + result.push_back(matrix[top][j]); + } + top++; + + if(left <= right && top <= bottom) { + for(int i=top; i<=bottom; i++) { + result.push_back(matrix[i][right]); + } + } + right--; + + if(left <= right && top <= bottom) { + for(int j=right; j>=left; j--) { + result.push_back(matrix[bottom][j]); + } + } + bottom--; + + if(left <= right && top <= bottom) { + for(int i=bottom; i>=top; i--) { + result.push_back(matrix[i][left]); + } + } + left++; + } + return result; + } +}; \ No newline at end of file