Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array1 Completed #1640

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
21 changes: 21 additions & 0 deletions Diagonal Traverse Question
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
498. Diagonal Traverse {Medium}

Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.

Example 1:

Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
Example 2:

Input: mat = [[1,2],[3,4]]
Output: [1,2,3,4]


Constraints:

m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
-105 <= mat[i][j] <= 105
56 changes: 56 additions & 0 deletions DiagonalTraverse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
Time Complexity: O(m*n) spiral traversal

Space Complexity: O(1) no extra space is used

Did this code successfully run on Leetcode : Yes
*/
class DiagonalTraverse {
public int[] findDiagonalOrder(int[][] mat)
{
int m = mat.length;
int n = mat[0].length;

int[] result = new int[m*n];
boolean dir = true; //direction = true meaning travelling upward else downward
int row = 0, col = 0;

for(int i = 0; i<m*n; i++)
{
result[i] = mat[row][col];

if(dir)
{
if(row == 0 && col != n-1) {
//Go to the next column and then change the direction to downward
col++;
dir = false;
}
else if(col == n-1) {
row++;
dir = false;
}
else {
row--; col++;
}
}
else //downward direction
{
if(col==0 && row !=m-1) {
//Go to the next row and then change the direction to upward
row++;
dir = true;
}
else if(row == m-1) {
col++;
dir = true;
}
else {
row++; col--;
}
}
}

return result;
}
}
27 changes: 27 additions & 0 deletions Product of Array Except Self Question
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
238. Product of Array Except Self {Medium}

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.


Example 1:

Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2:

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]


Constraints:

2 <= nums.length <= 105
-30 <= nums[i] <= 30
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.


Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
34 changes: 34 additions & 0 deletions ProductArrayExceptSelfBruteForce.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
Time Complexity: O(n)×O(n)=O(n^2).

The time complexity is O(n²), as there are two nested loops.
The outer loop iterates over each element in nums (O(n)).
The inner loop computes the product of all elements except nums[i] (O(n)).

Space Complexity: O(1)

Did this code successfully run on Leetcode : No Time Limit Exceeded for an input of nums[] which is [-1,....-1]
huge input with just -1.

This brute force approach is not optimal for large arrays due to its quadratic time complexity, but it provides
a straightforward way to solve the problem.

*/
public class ProductArrayExceptSelfBruteForce {
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) { // Exclude nums[i]
product *= nums[j];
}
}
result[i] = product; // Store the product in the result array
}

return result;
}
}
70 changes: 70 additions & 0 deletions ProductArrayExceptSelfUsingDivision.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
Time Complexity: O(n)+O(n)=O(2n)=O(n)
The time complexity of this approach is O(n), where n is the length of the input array nums.

We iterate through the array once to calculate totalProduct and zeroCount. O(n)
We iterate through the array again to populate the result array based on zeroCount. O(n)
Since both operations require only one pass through the array, the overall time complexity is O(n).

Space Complexity: O(1)
The space complexity is O(1) in terms of additional space, if we exclude the output array result (as required
by the problem’s constraints).

We use a constant amount of extra space for totalProduct and zeroCount.
The output array result is the only space we use beyond the input, and it does not count towards extra
space in this context.

Did this code successfully run on Leetcode : yes
*/

import java.util.Arrays;

public class ProductArrayExceptSelfUsingDivision {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;

// Step 1: Calculate the product of all non-zero elements and count zeros
int totalProduct = 1;
int zeroCount = 0;

for (int num : nums) {
if (num != 0) {
totalProduct *= num;
} else {
zeroCount++;
}
}

// Step 2: Create the result array based on zero count
int[] result = new int[n];

if (zeroCount > 1) {
// More than one zero, all results are zero
return result;
} else if (zeroCount == 1) {
// Exactly one zero, only the position with zero in `nums` gets the product
for (int i = 0; i < n; i++) {
if (nums[i] == 0) {
result[i] = totalProduct;
}
}
} else {
// No zeros, divide totalProduct by each element in `nums` to get result
for (int i = 0; i < n; i++) {
result[i] = totalProduct / nums[i];
}
}

return result;
}

public static void main(String[] args) {
ProductArrayExceptSelfUsingDivision sol = new ProductArrayExceptSelfUsingDivision();

int[] nums1 = {1, 2, 3, 4};
System.out.println(Arrays.toString(sol.productExceptSelf(nums1))); // Output: [24, 12, 8, 6]

int[] nums2 = {-1, 1, 0, -3, 3};
System.out.println(Arrays.toString(sol.productExceptSelf(nums2))); // Output: [0, 0, 9, 0, 0]
}
}
44 changes: 44 additions & 0 deletions ProductArrayExceptSelfWithoutDivision.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
Time Complexity: O(2n) two pass, one to find the left product and other to find the right product along with
updating the result

Space Complexity: O(1) no extra space used, the space used for result array will be returned as output which we do not
consider as input and output remains same.

Did this code successfully run on Leetcode : yes

This approach was explained in class
*/
class ProductArrayExceptSelfWithoutDivision {
public int[] productExceptSelf(int[] nums)
{
int n = nums.length;
int[] result = new int[n];

//left product
int rp = 1; //runningProduct
result[0] = rp;

/*
rp = rp*nums[i-1]

[2, 4, 6, 1]
RP=> 1, (1*2 = 2), (2*4 = 8), (8*6=48)
*/
for(int i = 1; i < n; i++)
{
rp = rp*nums[i-1];
result[i] = rp; //left products added in result
}

//right product
rp = 1;
for(int i = nums.length-2; i>=0; i--) //-2 as last value won't change
{
rp = rp*nums[i+1];
result[i] = result[i] * rp;
}

return result;
}
}
23 changes: 23 additions & 0 deletions Spiral Matrix Question
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
54. Spiral Matrix {Medium}

Given an m x n matrix, return all elements of the matrix in spiral order.

Example 1:


Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:


Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]


Constraints:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

72 changes: 72 additions & 0 deletions SpiralTraverse.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
Time Complexity: O(m*n) spiral traversal

Space Complexity: O(1) no extra space is used

Did this code successfully run on Leetcode : Yes

We can also do this with recursion
*/

import java.util.ArrayList;
import java.util.List;

class SpiralTraverse {
public List<Integer> spiralOrder(int[][] matrix) {

List<Integer> result = new ArrayList<>();
int m = matrix.length;
int n = matrix[0].length;

int top = 0, left = 0, bottom = m-1, right = n-1;

while(top <= bottom && left <= right)
{
/*
Whenever we are mutating base condition variables inside a loop, we need
to recheck it again before proceeding, here top, bottom, left and right change
so they are traversing the same elements again and again till all the 4 for loops
are done and then when it checks for while the loop breaks, to avoid this, we need
to make sure that for every for loop the condition in while holds true
*/

//1st for loop, nothing is mutated so no need to check
for(int i = left; i<=right; i++) {
result.add(matrix[top][i]);
}
top ++;

//Even though top changes above but the for loop will take care that top<=bottom
for(int i = top; i<=bottom; i++) {
result.add(matrix[i][right]);
}
right--;

/*
Here both top and right are mutated above, so here we need to check for top<=bottom,
regarding left and right is already handled in for loop
*/
if(top <= bottom)
{
for(int i = right; i>=left; i--) {
result.add(matrix[bottom][i]);
}
bottom--;
}

/*
Here everything mutated but top and bottom are taken care by for loop so we only
need to check for left and right
*/
if(left <= right)
{
for(int i=bottom; i>=top; i--) {
result.add(matrix[i][left]);
}
left++;
}
}

return result;
}
}
Loading