From 5d8d4edcf80afc62005d321ba3250741669707b3 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 21 Oct 2025 15:23:39 -0700 Subject: [PATCH] Done Arrays1 --- DiagonalTraversal.java | 47 ++++++++++++++++++++++++++++++++++++++++++ ProductExpectSelf.java | 22 ++++++++++++++++++++ SpiralMatrix.java | 45 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 114 insertions(+) create mode 100644 DiagonalTraversal.java create mode 100644 ProductExpectSelf.java create mode 100644 SpiralMatrix.java diff --git a/DiagonalTraversal.java b/DiagonalTraversal.java new file mode 100644 index 00000000..ba4a53d2 --- /dev/null +++ b/DiagonalTraversal.java @@ -0,0 +1,47 @@ +class Solution { + public int[] findDiagonalOrder(int[][] mat) { + int m = mat.length; + int n = mat[0].length; + + int[] result = new int[m*n]; + int r = 0, c = 0; + + boolean dir = true; + + for(int i = 0; i < m * n; i++) { + result[i] = mat[r][c]; + + if(dir) { + if(c == n - 1) { + r++; + dir = false; + } + else if(r == 0) { + c++; + dir = false; + } + else { + r--; c++; + } + } else { + if(r == m - 1) { + c++; + dir = true; + } + else if(c == 0) { + r++; + dir = true; + } + else { + r++; c--; + } + } + } + + return result; + } +} + + +Time Complexity : O(m*n) +Space Complexity : O(1) \ No newline at end of file diff --git a/ProductExpectSelf.java b/ProductExpectSelf.java new file mode 100644 index 00000000..9010542c --- /dev/null +++ b/ProductExpectSelf.java @@ -0,0 +1,22 @@ +class Solution { + public int[] productExceptSelf(int[] nums) { + int n = nums.length; + int[] result = new int[n]; + + for (int i = 0; i < n; i++) { + int product = 1; + + for (int j = 0; j < n; j++) { + if (i != j) { + product *= nums[j]; + } + } + result[i] = product; + } + return result; + } +} + + +Time Complexity : O(n^2) +Space Complexity : O(1) \ No newline at end of file diff --git a/SpiralMatrix.java b/SpiralMatrix.java new file mode 100644 index 00000000..6286c1f9 --- /dev/null +++ b/SpiralMatrix.java @@ -0,0 +1,45 @@ +class Solution { + public List spiralOrder(int[][] matrix) { + int m = matrix.length; + int n = matrix[0].length; + + int top = 0, bottom = m-1, left = 0, right = n-1; + + List result = new ArrayList<>(); + + while(top <= bottom && left <= right){ + + for(int i=left; i<=right; i++){ + result.add(matrix[top][i]); + } + top++; + + for(int i=top; i<=bottom; i++){ + result.add(matrix[i][right]); + } + right--; + + if(top <= bottom) + { + for(int i=right; i>=left; i--){ + result.add(matrix[bottom][i]); + } + bottom--; + } + + if(left <= right) + { + for(int i=bottom; i>=top; i--){ + result.add(matrix[i][left]); + } + left++; + } + } + + return result; + } +} + + +Time Complexity : O(m*n) +Space Complexity : O(1) \ No newline at end of file