# Array

### What is an Array?

1. **Arrays can store data of a specified type:** Arrays in most programming languages are designed to store elements of a specific data type. This means that all elements within an array must be of the same type. For example, an array of integers can only store integer values, and an array of strings can only store string values.
2. **Elements of an array are contiguous:** In memory, the elements of an array are stored in a contiguous (adjacent) manner. This means that the elements are stored one after another in a continuous block of memory. This contiguous arrangement allows for efficient access to array elements using their indices.
3. **Each element has a unique index:** Arrays use a zero-based indexing system, which means that each element in the array has a unique index associated with it. The index serves as a positional identifier for each element within the array. The first element in the array has an index of 0, the second element has an index of 1, and so on.
4. **The size is predefined and cannot be modified:** When an array is created, its size is predefined and fixed. Once the size is determined, it cannot be changed during the execution of the program. This means that the number of elements an array can hold is determined at the time of its declaration and cannot be dynamically adjusted.

### Types of Arrays

**Single-Dimensional Array:**

* Single row or sequence of elements.
* Example: `int n = 5; int[] array = new int[n];`

**Multi-Dimensional Array:**

* An array of arrays, with more than one dimension.
* Example: `int n = 3; int[][] matrix = new int[n][n];`

### Create 1D Array

When we create an array in Java, we follow these steps:

1. **Declare:** This step involves creating a reference to the array, specifying its type and name.
2. **Instantiation of Array:** In this step, we create the array object in memory by using the `new` keyword followed by the array type and size.
3. **Initialization:** Finally, we assign values to the individual cells or elements of the array.

Here's an example of Java code that demonstrates these steps:

```java
// Declare an integer array
int[] intArray;

// Instantiate the array with size 5
intArray = new int[5];

// Initialize array elements with values
intArray[0] = 10;
intArray[1] = 20;
intArray[2] = 30;
intArray[3] = 40;
intArray[4] = 50;

System.out.println(Arrays.toString(intArray));
```

### Insertion in 1D Array

**Example:**

```java
public class SingleDimensionArray {
    int arr[] = null;

    // Constructor to initialize the array with default values
    public SingleDimensionArray(int sizeOfArray) {
        arr = new int[sizeOfArray]; // Create an array with the specified size
        for (int i = 0; i < arr.length; i++) {
            arr[i] = Integer.MIN_VALUE; // Set each element to the minimum value for integers
        }
    }

    // Method to insert a value at a specific location in the array
    public void insert(int location, int valueToBeInserted) {
        try {
            if (arr[location] == Integer.MIN_VALUE) { // Check if the location is empty
                arr[location] = valueToBeInserted; // Insert the value at the specified location
                System.out.println("Successfully inserted");
            } else {
                System.out.println("This cell is already occupied");
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid index to access array");
        }
    }
}

```

**Explanation:**

```java
1: public class SingleDimensionArray {
```

This line declares a public class named `SingleDimensionArray`. A class serves as a blueprint for creating objects with specific properties and behaviors.

```java
2: 	int arr[] = null;
```

This line declares an integer array variable named `arr` and initializes it with a null value. It indicates that the array is currently empty.

```java
4: public SingleDimensionArray(int sizeOfArray) {
```

This line defines a constructor method for the `SingleDimensionArray` class, which takes an integer parameter `sizeOfArray`. The constructor is called when an object of the class is created and initializes the array with a specified size.

```java
5: 	arr = new int[sizeOfArray);
```

This line creates a new integer array object with a size equal to the `sizeOfArray` parameter passed to the constructor. The `new` keyword is used to allocate memory for the array.

```java
6: 	for (int i=0; i<arr.length; i++) {
```

This line starts a loop that iterates over each index of the `arr` array. It initializes a local integer variable `i` to 0 and continues the loop as long as `i` is less than the length of the `arr` array.

```java
7: 		arr[i] = Integer.MIN_VALUE;
```

This line assigns the value of `Integer.MIN_VALUE` (a constant representing the smallest possible integer value) to the element at index `i` of the `arr` array. This value is used as a marker to indicate that the cell is currently empty.

```java
9: public void insert(int location, int valueToBeInserted) {
```

This line defines a public method named `insert` that takes two integer parameters: `location` represents the index at which the value should be inserted, and `valueToBeInserted` represents the value to be inserted at that location.

```java
11: 		if (arr[location] == Integer.MIN_VALUE) {
```

This line checks if the element at the specified `location` in the `arr` array is equal to `Integer.MIN_VALUE`, indicating that the cell is currently empty.

```java
12: 			arr[location] = valueToBeInserted;
```

This line assigns the `valueToBeInserted` to the element at the specified `location` in the `arr` array.

```java
13: 			System.out.println("Successfully inserted");
```

This line prints the message "Successfully inserted" to the console, indicating that the value has been successfully inserted at the specified location.

```java
15: 			System.out.println("This cell is already occupied");
```

This line prints the message "This cell is already occupied" to the console if the element at the specified `location` is not equal to `Integer.MIN_VALUE`, indicating that the cell is already occupied with a value.

```java
18: catch (ArrayIndexOutOfBoundsException e) {
```

This line starts a catch block that handles an `ArrayIndexOutOfBoundsException` if it occurs within the preceding try block. This exception is thrown when the specified `location` is outside the valid range of indices for the `arr` array.

```java
19: 	System.out.println("Invalid index to access array");
```

This line prints the message "Invalid index to access array" to the console if an `ArrayIndexOutOfBoundsException` is caught, indicating that the specified `location` is invalid.

```java
22: }
```

This line marks the end of the `insert` method.

```java
24: }
```

This line marks the end of the \`SingleDimensionArray' class.

**Let's analyze the code and the output it produces when executed:**

```java
public static void main(String[] args) {
    SingleDimensionalArray sda = new SingleDimensionalArray(10);
    sda.insert(0, 0);
    sda.insert(1, 10);
    sda.insert(2, 20);
    sda.insert(1, 30);
    sda.insert(12, 120);
}
```

In this code, we have the `main` method, which serves as the entry point of the program. We create an instance of the `SingleDimensionalArray` class named `sda`, with a specified size of 10.

Then, we invoke the `insert` method on the `sda` object multiple times to insert values at different indices.

1. `sda.insert(0, 0);`
   * This inserts the value `0` at index `0`.
2. `sda.insert(1, 10);`
   * This inserts the value `10` at index `1`.
3. `sda.insert(2, 20);`
   * This inserts the value `20` at index `2`.
4. `sda.insert(1, 30);`
   * This attempts to insert the value `30` at index `1`, but since that index is already occupied, it will display a message indicating that the cell is already occupied.
5. `sda.insert(12, 120);`
   * This attempts to insert the value `120` at index `12`, which is outside the valid range of indices for the array. Therefore, it will display a message indicating an invalid index.

Now let's analyze the expected output:

```java
Successfully inserted
Successfully inserted
Successfully inserted
This cell is already occupied
Invalid index to access array
```

When the code runs, it will print the corresponding messages based on the operations performed:

* The first three insertions are successful, so the message "Successfully inserted" will be printed for each of them.
* The fourth insertion at index `1` fails because that cell is already occupied. Therefore, the message "This cell is already occupied" will be displayed.
* The fifth insertion at index `12` fails because it's an invalid index that exceeds the array size. Consequently, the message "Invalid index to access array" will be printed.

{% hint style="info" %}
The time complexity of a try-catch block is typically considered to be constant time, **O(1)**.
{% endhint %}

### Access 1D Element

{% code fullWidth="true" %}

```java
public static void main(String[] args) {
    SingleDimensionArray sda = new SingleDimensionArray(3); // Create a SingleDimensionArray object with size 3
    sda.insert(0, 10); // Insert 10 at index 0
    sda.insert(1, 20); // Insert 20 at index 1
    sda.insert(2, 30); // Insert 30 at index 2

    var firstElement = sda.arr[0]; // Access the value at index 0
    System.out.println(firstElement); // Print the value of the first element

    var thirdElement = sda.arr[2]; // Access the value at index 2
    System.out.println(thirdElement); // Print the value of the third element
}
```

{% endcode %}

In this code, the `main` method serves as the entry point of the program. We create an instance of the `SingleDimensionArray` class named `sda` with a size of 3.

Then, we invoke the `insert` method on the `sda` object to insert values at different indices:

1. `sda.insert(0, 10);`
   * This inserts the value `10` at index `0`.
2. `sda.insert(1, 20);`
   * This inserts the value `20` at index `1`.
3. `sda.insert(2, 30);`
   * This inserts the value `30` at index `2`.

After the insertions, we access the elements of the `arr` array using index access:

1. `var firstElement = sda.arr[0];`
   * This assigns the value of the first element of the `arr` array (`10`) to the `firstElement` variable.
2. `System.out.println(firstElement);`
   * This prints the value of `firstElement` to the console, which is `10`.
3. `var thirdElement = sda.arr[2];`
   * This assigns the value of the third element of the `arr` array (`30`) to the `thirdElement` variable.
4. `System.out.println(thirdElement);`
   * This prints the value of `thirdElement` to the console, which is `30`.

Now let's analyze the expected output:

```java
10
30
```

When the code runs, it will print the corresponding values of the `firstElement` and `thirdElement` variables, which are `10` and `30`, respectively.

{% hint style="info" %}
**Overall, the time complexity of the code is O(1) for individual insertions and accessing elements. The space complexity is O(1), where 3 is the size of the array created.**
{% endhint %}

***

### Traverse 1D Array

Let's analyze the code and the output it produces:

```java
public class SingleDimensionArray {
    int arr[] = null;

    // Constructor to initialize the array with default values
    public SingleDimensionArray(int sizeOfArray) {
        arr = new int[sizeOfArray]; // Create an array with the specified size
        for (int i = 0; i < arr.length; i++) {
            arr[i] = Integer.MIN_VALUE; // Set each element to the minimum value for integers
        }
    }

    // Method to insert a value at a specific location in the array
    public void insert(int location, int valueToBeInserted) {
        try {
            if (arr[location] == Integer.MIN_VALUE) { // Check if the location is empty
                arr[location] = valueToBeInserted; // Insert the value at the specified location
                System.out.println("Successfully inserted");
            } else {
                System.out.println("This cell is already occupied");
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid index to access array");
        }
    }

    // Method to traverse and print the elements of the array
    public void traverseArray() {
        try {
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " "); // Print each element separated by a space
            }
        } catch (Exception e) {
            System.out.println("Array no longer exists!");
        }
    }
}

public static void main(String[] args) {
    SingleDimensionArray sda = new SingleDimensionArray(10); // Create a SingleDimensionArray object with size 10
    sda.insert(0, 0); // Insert 0 at index 0
    sda.insert(1, 10); // Insert 10 at index 1
    sda.insert(2, 20); // Insert 20 at index 2
    sda.insert(1, 30); // Insert 30 at index 1 (overwriting the previous value)
    sda.insert(12, 120); // Attempt to insert at an invalid index

    System.out.println("Array Traversal down here");
    sda.traverseArray(); // Print the elements of the array
}
```

The code defines the `SingleDimensionArray` class, which has an array `arr` and three methods: `SingleDimensionArray` (the constructor), `insert`, and `traverseArray`.

In the `traverseArray` method:

* It tries to traverse the array and print its elements.
* If an exception occurs during the traversal (such as if the array is no longer accessible), it catches the exception and prints "Array no longer exists!"

In the `main` method:

* A `SingleDimensionArray` object `sda` is created with a size of 10.
* Values are inserted at various locations using the `insert` method.
* The `traverseArray` method is called to print the elements of the array.
* The message "Array Traversal down here" is printed.
* The `traverseArray` method is called again.

Now let's analyze the output:

```java
Successfully inserted
Successfully inserted
Successfully inserted
This cell is already occupied
Invalid index to access array
Array Traversal down here
0 10 20 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648
```

Explanation:

* The first three insertions are successful, so the messages "Successfully inserted" are printed for each of them.
* The fourth insertion at index 1 fails because that cell is already occupied, so the message "This cell is already occupied" is displayed.
* The fifth insertion at index 12 fails because it's an invalid index that exceeds the array size, so the message "Invalid index to access array" is printed.
* After the insertions, the `traverseArray` method is called, which prints the elements of the array. In this case, since only the first three elements were successfully inserted, the remaining elements are uninitialized and set to their default value, which is `Integer.MIN_VALUE` (-2147483648 in this case). Therefore, the output is "0 10 20 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648".

{% hint style="info" %}
The time complexity of the `traverseArray` method is **O(n)**, where n is the size of the array. It iterates over each element of the array and prints it.
{% endhint %}

***

### Finding Array Element (`Linear Search`)

```java
public class SingleDimensionArray {
    int arr[] = null;

    // Constructor to initialize the array with default values
    public SingleDimensionArray(int sizeOfArray) {
        arr = new int[sizeOfArray]; // Create an array with the specified size
        for (int i = 0; i < arr.length; i++) {
            arr[i] = Integer.MIN_VALUE; // Set each element to the minimum value for integers
        }
    }

    // Method to insert a value at a specific location in the array
    public void insert(int location, int valueToBeInserted) {
        try {
            if (arr[location] == Integer.MIN_VALUE) { // Check if the location is empty
                arr[location] = valueToBeInserted; // Insert the value at the specified location
                System.out.println("Successfully inserted");
            } else {
                System.out.println("This cell is already occupied");
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid index to access array");
        }
    }

    // Method to traverse and print the elements of the array
    public void traverseArray() {
        try {
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " "); // Print each element separated by a space
            }
        } catch (Exception e) {
            System.out.println("Array no longer exists!");
        }
    }

    // Method to search for an element in the array
    public void searchInArray(int valueToSearch) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == valueToSearch) {
                System.out.println("Value is found at the index of " + i);
                return;
            }
        }
        System.out.println(valueToSearch + " is not found");
    }
}

public static void main(String[] args) {
    SingleDimensionArray sda = new SingleDimensionArray(10); // Create a SingleDimensionArray object with size 10
    sda.insert(0, 10); // Insert 10 at index 0
    sda.insert(1, 20); // Insert 20 at index 1
    sda.insert(2, 30); // Insert 30 at index 2

    sda.searchInArray(40); // Search for the value 40 in the array
}
```

The code defines the `SingleDimensionArray` class with an array `arr` and four methods: `SingleDimensionArray` (the constructor), `insert`, `traverseArray`, and `searchInArray`.

In the `searchInArray` method:

* It searches for a given value in the array.
* It iterates over each element of the array and checks if it matches the value to search.
* If a match is found, it prints the index where the value is found.
* If no match is found, it prints a message indicating that the value was not found.

In the `main` method:

* A `SingleDimensionArray` object `sda` is created with a size of 10.
* Values are inserted at indices 0, 1, and 2 using the `insert` method.
* The `searchInArray` method is called to search for the value 40.

Now let's analyze the output:

```java
Successfully inserted
Successfully inserted
Successfully inserted
40 is not found
```

Explanation:

* The first three insertions at indices 0, 1, and 2 are successful, so "Successfully inserted" is printed three times.
* The `searchInArray` method searches for the value 40, which is not present in the array, so "40 is not found" is printed.

{% hint style="info" %}

**Time Complexity:**

* The time complexity of the `searchInArray` method is O(n), where n is the size of the array. It iterates over each element of the array to search for a specific value.

**Space Complexity:**

* The space complexity is O(n), where n is the size of the array. The memory required is proportional to the size of the array.
  {% endhint %}

***

### Delete an Element

```java
public class SingleDimensionArray {
    int arr[] = null;

    // Constructor to initialize the array with default values
    public SingleDimensionArray(int sizeOfArray) {
        arr = new int[sizeOfArray]; // Create an array with the specified size
        for (int i = 0; i < arr.length; i++) {
            arr[i] = Integer.MIN_VALUE; // Set each element to the minimum value for integers
        }
    }

    // Method to insert a value at a specific location in the array
    public void insert(int location, int valueToBeInserted) {
        try {
            if (arr[location] == Integer.MIN_VALUE) { // Check if the location is empty
                arr[location] = valueToBeInserted; // Insert the value at the specified location
                System.out.println("Successfully inserted");
            } else {
                System.out.println("This cell is already occupied");
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid index to access array");
        }
    }

    // Method to traverse and print the elements of the array
    public void traverseArray() {
        try {
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " "); // Print each element separated by a space
            }
        } catch (Exception e) {
            System.out.println("Array no longer exists!");
        }
    }

    // Method to search for an element in the array
    public void searchInArray(int valueToSearch) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == valueToSearch) {
                System.out.println("Value is found at the index of " + i);
                return;
            }
        }
        System.out.println(valueToSearch + " is not found");
    }

    // Method to delete a value from the array
    public void deleteValue(int valueToDeleteIndex) {
        try {
            arr[valueToDeleteIndex] = Integer.MIN_VALUE; // Delete the value by setting it to the minimum value
            System.out.println("The value has been deleted successfully.");

        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("The value provided is not in the range of the array.");
        }
    }

    public static void main(String[] args) {
        SingleDimensionArray sda = new SingleDimensionArray(10); // Create a SingleDimensionArray object with size 10
        sda.insert(0, 0); // Insert 0 at index 0
        sda.insert(1, 10); // Insert 10 at index 1
        sda.insert(2, 20); // Insert 20 at index 2

        sda.deleteValue(0); // Delete the value at index 0
        System.out.println(sda.arr[0]); // Print the value at index 0
    }
}
```

The code defines the `SingleDimensionArray` class with an array `arr` and five methods: `SingleDimensionArray` (the constructor), `insert`, `traverseArray`, `searchInArray`, and `deleteValue`.

In the `deleteValue` method:

* It tries to delete a value at the specified index in the array.
* It sets the value at the given index to `Integer.MIN_VALUE` to indicate deletion and print "The value has been deleted successfully."
* If the specified index is invalid (out of bounds), it catches the `ArrayIndexOutOfBoundsException` and prints "The value provided is not in the range of the array."

In the `main` method:

* An instance of `SingleDimensionArray` is created with a size of 10.
* Three insertions are performed at indices 0, 1, and 2.
* The `deleteValue` method is called to delete the value at index 0.
* Finally, the value at index 0 is printed, which should be `Integer.MIN_VALUE` since it was deleted.

The output of the code is:

```java
Successfully inserted
Successfully inserted
Successfully inserted
The value has been deleted successfully.
-2147483648
```

Explanation:

* The first three insertions are successful, so "Successfully inserted" is printed three times.
* The `deleteValue` method deletes the value at index 0, so "The value has been deleted successfully" is printed.
* Finally, `sda.arr[0]` is printed, which should be `Integer.MIN_VALUE` since the value at index 0 was deleted.

{% hint style="info" %}
**Time Complexity:**

* The time complexity of the `deleteValue` method is O(1) because it directly modifies a specific location in the array.

**Space Complexity:**

* The space complexity is O(n), where n is the size of the array. The memory required is proportional to the size of the array.&#x20;
  {% endhint %}

### Time and Space Complexity of 1D Arrays

<table data-full-width="true"><thead><tr><th>Operation</th><th>Time Complexity</th><th>Space Complexity</th></tr></thead><tbody><tr><td>Creating an empty array</td><td>O(1)</td><td>O(n)</td></tr><tr><td>Inserting a value in an array</td><td>O(1)</td><td>O(1)</td></tr><tr><td>Traversing a given array</td><td>O(n)</td><td>O(1)</td></tr><tr><td>Accessing a given cell</td><td>O(1)</td><td>O(1)</td></tr><tr><td>Searching a given value</td><td>O(n)</td><td>O(1)</td></tr><tr><td>Deleting a given value</td><td>O(1)</td><td>O(1)</td></tr></tbody></table>

***

### Create 2D Array

```java
import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    
    //Step 1 - Declaration
    int[][] int2dArray;

    //Step 2 - Instantiate
    int2dArray = new int[2][2];

    //Step 3 - Initialize
    int2dArray[0][0] = 1;
    int2dArray[0][1] = 2;
    int2dArray[1][0] = 3;
    int2dArray[1][1] = 4;

    System.out.println(Arrays.deepToString(int2dArray));

    //All Together
    String s2dArray[][] = {{"a","b"}, {"c","d"}};
    System.out.println(Arrays.deepToString(s2dArray));
    
  }
}
```

The provided code demonstrates the declaration, instantiation, initialization, and printing of a two-dimensional array in Java.

Here's a breakdown of the code:

1. Declaration:

   ```java
   int[][] int2dArray;
   ```

   This line declares a variable `int2dArray` of type `int[][]`, which represents a two-dimensional array of integers.
2. Instantiation:

   ```java
   int2dArray = new int[2][2];
   ```

   This line creates a new two-dimensional integer array with a size of 2x2. It assigns the newly created array to the `int2dArray` variable.
3. Initialization:

   ```java
   int2dArray[0][0] = 1;
   int2dArray[0][1] = 2;
   int2dArray[1][0] = 3;
   int2dArray[1][1] = 4;
   ```

   These lines initialize the individual elements of the `int2dArray` with specific values. For example, `int2dArray[0][0]` is assigned the value 1, `int2dArray[0][1]` is assigned the value 2, and so on.
4. Printing the Array:

   ```java
   System.out.println(Arrays.deepToString(int2dArray));
   ```

   This line uses the `Arrays.deepToString()` method to convert the two-dimensional array to a string representation and prints it to the console. It displays the contents of the `int2dArray` in the format \[\[1, 2], \[3, 4]].
5. Creating and Printing a String 2D Array:

   ```java
   String s2dArray[][] = {{"a","b"}, {"c","d"}};
   System.out.println(Arrays.deepToString(s2dArray));
   ```

   These lines declare and instantiate a two-dimensional string array `s2dArray` with values "a", and "b" in the first row and "c", and "d" in the second row. It then prints the contents of `s2dArray` using `Arrays.deepToString()`.

{% hint style="info" %}
**The time complexity of the code is O(mn), where m and n represent the dimensions of the two-dimensional array. The code initializes each element of the array individually, which takes constant time. Therefore, the time complexity is directly proportional to the total number of elements in the array.**

**The space complexity of the code is also O(mn) because it creates a two-dimensional array of size m x n. The space required is directly proportional to the number of elements in the array.**
{% endhint %}

***

### Insertion in 2D Array

The provided code demonstrates the implementation of a two-dimensional array in Java with insertion functionality. It also includes a test in the main method to insert a value into the array and print the array using `Arrays.deepToString()`.

Here's an explanation of the code and the output:

1. Class Definition:

   ```java
   public class TwoDimensionalArray {
     int arr[][] = null;

     // Constructor
     public TwoDimensionalArray(int numberOfRows, int numberOfColumns) {
       this.arr = new int[numberOfRows][numberOfColumns];

       // Initializing the array with Integer.MIN_VALUE
       for (int row = 0; row < arr[0].length; row++) {
         for (int col = 0; col < arr[0].length; col++) {
           arr[row][col] = Integer.MIN_VALUE;
         }
       }
     }

     // Insertion
     public void insertValueInTheArray(int row, int col, int value) {
       try {
         if (arr[row][col] == Integer.MIN_VALUE) {
           arr[row][col] = value;
           System.out.println("The value is successfully inserted");
         } else {
           System.out.println("This cell is already occupied");
         }
       } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Invalid index for 2D Array");
       }
     }
   }
   ```

   The `TwoDimensionalArray` class contains the definition of the array and the `insertValueInTheArray()` method for inserting values into the array. The constructor initializes the array with a specified number of rows and columns, and each element is set to `Integer.MIN_VALUE` as a default value.
2. Main Method:

   ```java
   import java.util.Arrays;

   class Main {
     public static void main(String[] args) {

       TwoDimensionalArray sda = new TwoDimensionalArray(3, 3);
       sda.insertValueInTheArray(0, 0, 10);
       System.out.println(Arrays.deepToString(sda.arr));

     }
   }
   ```

   In the `main` method, an instance of `TwoDimensionalArray` is created with 3 rows and 3 columns. The `insertValueInTheArray()` method is then called to insert the value 10 at the specified row 0 and column 0. Finally, `Arrays.deepToString()` is used to print the array.

Output:

```java
The value is successfully inserted
[[10, -2147483648, -2147483648], [-2147483648, -2147483648, -2147483648], [-2147483648, -2147483648, -2147483648]]
```

The output indicates that the value 10 was successfully inserted at the specified position (0, 0) in the two-dimensional array. The `Arrays.deepToString()` method is used to convert the two-dimensional array to a string representation, which is then printed to the console. The resulting string displays the contents of the array with the updated value. The other elements in the array are still set to `Integer.MIN_VALUE` as they were initialized in the constructor.

The `insertValueInTheArray()` method has a ⏱️ time complexity of O(1) and a 💾 space complexity of O(1).

{% hint style="info" %}
**⏱️ Time Complexity: The insertion operation is performed in constant time, regardless of the array's size or the insertion position. It directly accesses the array element using the provided indices, without any iteration. Hence, it has a time complexity of O(1).**

**💾 Space Complexity: The method's space complexity is also constant. It only uses a fixed amount of memory to store parameters and local variables, which doesn't change with the input size. Therefore, the space complexity is O(1).**
{% endhint %}

***

### Access 2D Element

```java
public class TwoDimensionalArray {
  int arr[][] = null; // 2D integer array to hold the values

  // Constructor
  public TwoDimensionalArray(int numberOfRows, int numberOfColumns) {
    this.arr = new int[numberOfRows][numberOfColumns]; // Initializing the 2D array with specified number of rows and columns

    // Initializing the array with Integer.MIN_VALUE
    for (int row = 0; row < arr[0].length; row++) { // loop through each row
      for (int col = 0; col < arr[0].length; col++) { // loop through each column
        arr[row][col] = Integer.MIN_VALUE; // Assign minimum integer value to each cell in the 2D array
      }
    }
  }

  // Insertion
  public void insertValueInTheArray(int row, int col, int value) {
    try {
      if (arr[row][col] == Integer.MIN_VALUE) { // If cell is empty
        arr[row][col] = value; // Insert the value to the 2D array
        System.out.println("The value is successfully inserted");
      } else {
        System.out.println("This cell is already occupied"); // If the cell is already occupied
      }
    } catch (ArrayIndexOutOfBoundsException e) { // Catch if row or column index is out of bounds
      System.out.println("Invalid index for 2D Array");
    }
  }

  //Access Cell
  public void accessCell(int row, int col) {
    System.out.println("\\\\nAccessing Row " + row + ", Col " + col);
    try {
      System.out.println("Cell value is: " + arr[row][col]); // Access the cell value of the specified row and column
    } catch (ArrayIndexOutOfBoundsException e) { // Catch if row or column index is out of bounds
      System.out.println("Invalid index of 2D array");
    }
  }
}

```

This class defines a two-dimensional array of integers, along with methods to insert values into the array and access cell values. Here's a summary of each method:

* The `TwoDimensionalArray` constructor initializes the 2D array with a specified number of rows and columns and sets each cell to the minimum integer value.
* The `accessCell` method accesses the value of a specified row and column in the 2D array. If the row or column index is out of bounds, it prints a message indicating that the index is invalid.

Here is an example of how to use this class:

```java
TwoDimensionalArray sda = new TwoDimensionalArray(3, 3); // Create a 2D array with 3 rows and 3 columns
sda.insertValueInTheArray(0, 0, 10); // Insert 10 into the cell at row 0 and column 0
sda.insertValueInTheArray(0, 1, 20); // Insert 20 into the cell at row 0 and column 1
sda.accessCell(0, 1); // Access the cell value at row 0 and column 1

```

The output of this code should be:

```java
The value is successfully inserted
The value is successfully inserted

Accessing Row 0, Col 1
Cell value is: 20

```

This output indicates that the values 10 and 20 were successfully inserted into the 2D array and that the value 20 was accessed using the `accessCell` method.

{% hint style="info" %}
**The time complexity for inserting a value into the 2D array is O(1) because it only involves assigning a value to a specific cell. The time complexity for accessing a cell value is also O(1) because it only involves accessing the value of a specific cell.**

**The space complexity of this class is O(n^2), where n is the number of rows or columns in the 2D array because it requires creating a 2D array to hold the values.**
{% endhint %}

***

### Traverse a 2D Array

```java
public class TwoDimensionalArray {
  int arr[][] = null; // 2D integer array to hold the values

  // Constructor
  public TwoDimensionalArray(int numberOfRows, int numberOfColumns) {
    this.arr = new int[numberOfRows][numberOfColumns]; // Initializing the 2D array with specified number of rows and columns

    // Initializing the array with Integer.MIN_VALUE
    for (int row = 0; row < arr[0].length; row++) { // loop through each row
      for (int col = 0; col < arr[0].length; col++) { // loop through each column
        arr[row][col] = Integer.MIN_VALUE; // Assign minimum integer value to each cell in the 2D array
      }
    }
  }

  // Insertion
  public void insertValueInTheArray(int row, int col, int value) {
    try {
      if (arr[row][col] == Integer.MIN_VALUE) { // If cell is empty
        arr[row][col] = value; // Insert the value to the 2D array
        System.out.println("The value is successfully inserted");
      } else {
        System.out.println("This cell is already occupied"); // If the cell is already occupied
      }
    } catch (ArrayIndexOutOfBoundsException e) { // Catch if row or column index is out of bounds
      System.out.println("Invalid index for 2D Array");
    }
  }

	//Access Cell
  public void accessCell(int row, int col) {
    System.out.println("\\nAccessing Row " + row + ", Col " + col);
    try {
      System.out.println("Cell value is: " + arr[row][col]); // Access the cell value of the specified row and column
    } catch (ArrayIndexOutOfBoundsException e) { // Catch if row or column index is out of bounds
      System.out.println("Invalid index of 2D array");
    }
  }

	//Traverse 2D Array
	public void traverse2DArray() {
	  // Loop through each row of the 2D array
	  for (int row = 0; row < arr.length; row++) {
	    // Loop through each column of the current row
	    for (int col = 0; col < arr[row].length; col++) {
	      // Print the value of the current cell followed by a space
	      System.out.print(arr[row][col] + " ");
	    }
	    // Print a newline character to move to the next row
	    System.out.println();
	  }
	}

}
```

Main Method:

```java
import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    
   TwoDimensionalArray sda = new TwoDimensionalArray(3,3);
    sda.insertValueInTheArray(0,0, 10);
    sda.insertValueInTheArray(0,1, 20);
    sda.insertValueInTheArray(1,0, 30);
    sda.insertValueInTheArray(2,0, 40);

    sda.traverse2DArray();
    
  }
}
```

The output of the given Java program would be:

```java
10 20 2147483647
30 2147483647 2147483647
40 2147483647 2147483647
```

{% hint style="info" %}
**The time complexity of the `traverse2DArray` method is O(mn), where m is the number of rows in the 2D array and n is the number of columns.**
{% endhint %}

***

### Finding 2D Array Element

```java
public class TwoDimensionalArray {
  int arr[][] = null; // 2D integer array to hold the values

  // Constructor
  public TwoDimensionalArray(int numberOfRows, int numberOfColumns) {
    this.arr = new int[numberOfRows][numberOfColumns]; // Initializing the 2D array with specified number of rows and columns

    // Initializing the array with Integer.MIN_VALUE
    for (int row = 0; row < arr[0].length; row++) { // loop through each row
      for (int col = 0; col < arr[0].length; col++) { // loop through each column
        arr[row][col] = Integer.MIN_VALUE; // Assign minimum integer value to each cell in the 2D array
      }
    }
  }

  // Insertion
  public void insertValueInTheArray(int row, int col, int value) {
    try {
      if (arr[row][col] == Integer.MIN_VALUE) { // If cell is empty
        arr[row][col] = value; // Insert the value to the 2D array
        System.out.println("The value is successfully inserted");
      } else {
        System.out.println("This cell is already occupied"); // If the cell is already occupied
      }
    } catch (ArrayIndexOutOfBoundsException e) { // Catch if row or column index is out of bounds
      System.out.println("Invalid index for 2D Array");
    }
  }

	//Access Cell
  public void accessCell(int row, int col) {
    System.out.println("\\nAccessing Row " + row + ", Col " + col);
    try {
      System.out.println("Cell value is: " + arr[row][col]); // Access the cell value of the specified row and column
    } catch (ArrayIndexOutOfBoundsException e) { // Catch if row or column index is out of bounds
      System.out.println("Invalid index of 2D array");
    }
  }

	//Traverse 2D Array
	public void traverse2DArray() {
	  // Loop through each row of the 2D array
	  for (int row = 0; row < arr.length; row++) {
	    // Loop through each column of the current row
	    for (int col = 0; col < arr[row].length; col++) {
	      // Print the value of the current cell followed by a space
	      System.out.print(arr[row][col] + " ");
	    }
	    // Print a newline character to move to the next row
	    System.out.println();
	  }
	}

//Search 2D Element
public void searchValue(int value) {
    // Iterate through each row of the 2D array 'arr'
    for (int row = 0; row < arr.length; row++) {
        // Iterate through each column of the current row
        for (int col = 0; col < arr[0].length; col++) {
            // Check if the current element matches the search value
            if (arr[row][col] == value) {
                // If a match is found, print the row and column position and exit the method
                System.out.println("Value is found at row: " + row + " Col: " + col);
                return;
            }
        }
    }
    // If the loop completes without finding the value, print that the value was not found
    System.out.println("Value is not found");
}
  
}
```

Main Method:

```java
import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    
   TwoDimensionalArray sda = new TwoDimensionalArray(3,3);
    sda.insertValueInTheArray(0,0, 10);
    sda.insertValueInTheArray(0,1, 20);
    sda.insertValueInTheArray(1,0, 30);
    sda.insertValueInTheArray(2,0, 40);

    sda.searchValue(20);
    
  }
}
```

Output:

```java
The value is successfully inserted
The value is successfully inserted
The value is successfully inserted
The value is successfully inserted
Value is found at row: 0 Col: 1
```

{% hint style="info" %}
**The time complexity of the `searchValue` method is O(mn), where m is the number of rows in the 2D array and n is the number of columns.**
{% endhint %}

Explanation:

The code represents a method called `searchValue` that takes an integer parameter named `value`. Here's an explanation of each part of the code:

1. The method is defined as `public`, which means it can be accessed from other parts of the program.
2. The method has a loop that iterates through each row of a two-dimensional array called `arr`. The loop initializes a variable `row` to 0, and as long as `row` is less than the length of `arr`, the loop continues. After each iteration, the `row` variable is incremented by 1.
3. Inside the outer loop, there is an inner loop that iterates through each column of the current row. The loop initializes a variable `col` to 0, and as long as `col` is less than the length of the first row of `arr` (assuming that all rows have the same length), the loop continues. After each iteration, the `col` variable is incremented by 1.
4. Within the inner loop, there is an `if` statement that checks if the current element in `arr` (at the `row` and `col` indices) is equal to the `value` passed to the method. If there is a match, it means the desired value has been found.
5. If a match is found, the code prints a message indicating the position of the value in the array. The message includes the values of `row` and `col` concatenated with the appropriate strings. After printing the message, the `return` statement is used to exit the method, as there is no need to continue searching.
6. If the loops are complete without finding a match, it means the desired value was not found. In this case, the code reaches the line outside the loops and prints a message indicating that the value was not found.

To summarize, the code searches for a specific `value` within a two-dimensional array `arr`. It iterates through each element of the array and checks if the current element matches the desired value. If a match is found, it prints the position of the value and exits the method. If the value is not found, it prints a message indicating that.

***

### Delete 2D Array

```java
public class TwoDimensionalArray {
  int arr[][] = null; // 2D integer array to hold the values

  // Constructor
  public TwoDimensionalArray(int numberOfRows, int numberOfColumns) {
    this.arr = new int[numberOfRows][numberOfColumns]; // Initializing the 2D array with specified number of rows and columns

    // Initializing the array with Integer.MIN_VALUE
    for (int row = 0; row < arr[0].length; row++) { // loop through each row
      for (int col = 0; col < arr[0].length; col++) { // loop through each column
        arr[row][col] = Integer.MIN_VALUE; // Assign minimum integer value to each cell in the 2D array
      }
    }
  }

  // Insertion
  public void insertValueInTheArray(int row, int col, int value) {
    try {
      if (arr[row][col] == Integer.MIN_VALUE) { // If cell is empty
        arr[row][col] = value; // Insert the value to the 2D array
        System.out.println("The value is successfully inserted");
      } else {
        System.out.println("This cell is already occupied"); // If the cell is already occupied
      }
    } catch (ArrayIndexOutOfBoundsException e) { // Catch if row or column index is out of bounds
      System.out.println("Invalid index for 2D Array");
    }
  }

	//Access Cell
  public void accessCell(int row, int col) {
    System.out.println("\\nAccessing Row " + row + ", Col " + col);
    try {
      System.out.println("Cell value is: " + arr[row][col]); // Access the cell value of the specified row and column
    } catch (ArrayIndexOutOfBoundsException e) { // Catch if row or column index is out of bounds
      System.out.println("Invalid index of 2D array");
    }
  }

	//Traverse 2D Array
	public void traverse2DArray() {
	  // Loop through each row of the 2D array
	  for (int row = 0; row < arr.length; row++) {
	    // Loop through each column of the current row
	    for (int col = 0; col < arr[row].length; col++) {
	      // Print the value of the current cell followed by a space
	      System.out.print(arr[row][col] + " ");
	    }
	    // Print a newline character to move to the next row
	    System.out.println();
	  }
	}

//Search 2D Element
public void searchValue(int value) {
    // Iterate through each row of the 2D array 'arr'
    for (int row = 0; row < arr.length; row++) {
        // Iterate through each column of the current row
        for (int col = 0; col < arr[0].length; col++) {
            // Check if the current element matches the search value
            if (arr[row][col] == value) {
                // If a match is found, print the row and column position and exit the method
                System.out.println("Value is found at row: " + row + " Col: " + col);
                return;
            }
        }
    }
    // If the loop completes without finding the value, print that the value was not found
    System.out.println("Value is not found");
}
  
// Delete 2D Value
public void deleteValue(int row, int col) {
  try {
    // Print a message indicating the value that is being deleted
    System.out.println("Successfully deleted: " + arr[row][col]);
    
    // Set the value at the specified row and column indices to the minimum possible integer value
    arr[row][col] = Integer.MIN_VALUE;
  } catch (ArrayIndexOutOfBoundsException e) {
    // Handle the exception if the provided indices are not valid for the array
    System.out.println("This index is not valid for the array");
  }
}

}
```

Main Method:

```java
import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    
   TwoDimensionalArray sda = new TwoDimensionalArray(3,3);
    sda.insertValueInTheArray(0,0, 10);
    sda.insertValueInTheArray(0,1, 20);
    sda.insertValueInTheArray(1,0, 30);
    sda.insertValueInTheArray(2,0, 40);

    System.out.println(Arrays.deepToString(sda.arr));
    sda.deleteValue(0,0);
    System.out.println(Arrays.deepToString(sda.arr))
    
  }
}
```

Output:

```java
The value is successfully inserted
The value is successfully inserted
The value is successfully inserted
The value is successfully inserted
[[10, 20, -2147483648], [30, -2147483648, -2147483648], [40, -2147483648, -2147483648]]
Succesfully deleted: 10
[[-2147483648, 20, -2147483648], [30, -2147483648, -2147483648], [40, -2147483648, -2147483648]]
```

{% hint style="info" %}
&#x20;**The time complexity is O(1) because we are printing a message to the console.**
{% endhint %}

Explanation:

1. The method is declared as `public`, indicating it can be accessed from other parts of the program. It takes two integer parameters, `row` and `col`, representing the row and column indices of a two-dimensional array.
2. The method tries to perform the deletion of a value at the specified `row` and `col` indices. It does this by assigning `Integer.MIN_VALUE` (the minimum possible integer value in Java) to the element at `arr[row][col]`. This effectively marks the value as deleted or removed from the array.
3. The `try` block is used to encapsulate the code that might throw an `ArrayIndexOutOfBoundsException`. This exception occurs when the provided indices are outside the valid range for the array.
4. If the code inside the `try` block executes successfully, it means the deletion was performed without any errors. In that case, a message is printed to indicate the successful deletion, including the value that was deleted, which is obtained from `arr[row][col]`.
5. If an `ArrayIndexOutOfBoundsException` occurs, the code inside the corresponding `catch` block is executed. It catches the exception and handles it gracefully by printing a message indicating that the provided indices are not valid for the array.

To summarize, the `deleteValue` method aims to delete a value from a two-dimensional array `arr` at the specified `row` and `col` indices. It uses a try-catch mechanism to handle any potential out-of-bounds exceptions, ensuring that the program does not crash if the provided indices are invalid. If the deletion is successful, it prints a message indicating the successful deletion, and if the indices are invalid, it prints a message informing the user about the invalid index for the array.

***

### Time and Space Complexity of 2D Array

<table data-full-width="true"><thead><tr><th>Operation</th><th>Time Complexity</th><th>Space Complexity</th></tr></thead><tbody><tr><td>Creating an empty array</td><td>O(1)</td><td>O(mn)</td></tr><tr><td>Inserting a value in an array</td><td>O(1)</td><td>O(1)</td></tr><tr><td>Traversing a given array</td><td>O(mn)</td><td>O(1)</td></tr><tr><td>Accessing a given cell</td><td>O(1)</td><td>O(1)</td></tr><tr><td>Searching a given value</td><td>O(mn)</td><td>O(1)</td></tr><tr><td>Deleting a given value</td><td>O(1)</td><td>O(1)</td></tr></tbody></table>

1. Creating an empty array:
   * Time Complexity: O(1) ⏱️ - Creating an empty array takes constant time because it doesn't depend on the array size. Whether the array is small or large, the time to create an empty array remains the same.
   * Space Complexity: O(mn) 🧠 - The space complexity is O(mn) because it allocates memory for an array with m rows and n columns. The space required is proportional to the size of the array.
2. Inserting a value in an array:
   * Time Complexity: O(1) ⏱️ - Inserting a value at a specific location in a 2D array takes constant time because it directly accesses the desired cell using the row and column indices. The operation time doesn't depend on the array size.
   * Space Complexity: O(1) 🧠 - Inserting a value doesn't require additional space as it modifies the existing array. It doesn't affect the overall space complexity.
3. Traversing a given array:
   * Time Complexity: O(mn) ⏱️ - Traversing or iterating through a 2D array with m rows and n columns requires visiting each element once. The time complexity is proportional to the number of elements in the array, which is m \* n.
   * Space Complexity: O(1) 🧠 - Traversing the array doesn't require any additional space as it only uses variables to store the indices. The space complexity remains constant.
4. Accessing a given cell:
   * Time Complexity: O(1) ⏱️ - Accessing a specific cell in a 2D array takes constant time because it directly accesses the cell using the row and column indices. The operation time is not dependent on the array size.
   * Space Complexity: O(1) 🧠 - Accessing a cell doesn't require additional space as it retrieves the value from the existing array. The space complexity remains constant.
5. Searching a given value:
   * Time Complexity: O(mn) ⏱️ - Searching for a given value in a 2D array requires checking each element to find a match. In the worst case, if the value is not present, it may need to iterate through all mn elements. Thus, the time complexity is proportional to the number of elements in the array.
   * Space Complexity: O(1) 🧠 - Searching a value doesn't require additional space as it only uses variables to store indices and the search value. The space complexity remains constant.
6. Deleting a given value:
   * Time Complexity: O(1) ⏱️ - Deleting a given value from a 2D array takes constant time because it directly accesses and modifies the cell containing the value. The operation time is not dependent on the array size.
   * Space Complexity: O(1) 🧠 - Deleting a value doesn't require additional space as it modifies the existing array. The space complexity remains constant.

***

## When to Use/Avoid Arrays

When to Use Arrays: 🔹 To store multiple variables of the same data type: Arrays are perfect when you need to group together multiple elements of the same kind. They allow you to efficiently store and access these elements as a single unit.

🔹 Random access: Arrays provide direct and fast access to individual elements using an index. This means you can easily retrieve any element from the array by specifying its position, which is particularly useful for searching, sorting, or manipulating data.

When to Avoid Arrays: ❌ Same data type elements: If you have a collection of different data types, arrays may not be the best choice. Arrays require all elements to have the same data type, so if you need to store a mixture of data types (such as strings, numbers, and booleans), you'll need to consider other data structures.

❌ Reserve memory: Arrays require contiguous blocks of memory to store their elements. If you're unsure of the number of elements you'll need or if the size of your data is dynamic, arrays might not be the most efficient choice. In such cases, dynamic data structures like lists or linked lists may be more suitable.

{% hint style="info" %}
Remember, the key takeaways are:

🌟 Arrays are great for grouping variables of the same data type and enabling random access to elements. 🌟 If you have different data types or if your data size is dynamic, other data structures might be more appropriate to use instead of arrays.
{% endhint %}

***

## Array Project

### **Calculate Average Temperature**

{% code fullWidth="true" %}

```java
import java.util.*;

class Main {
  public static void main(String[] args) {
    Scanner console = new Scanner(System.in); // Create a Scanner object to read user input
    System.out.print("How many days' temperature?"); // Prompt the user to enter the number of days
    int numDays = console.nextInt(); // Read the number of days entered by the user and store it in the numDays variable

    int sum = 0; // Initialize a variable to store the sum of temperatures
    for (int i=1; i<=numDays; i++) { // Start a loop from 1 to numDays (inclusive)
      System.out.print("Day " + i + "'s high temp: "); // Prompt the user to enter the high temperature for each day
      int next = console.nextInt(); // Read the temperature entered by the user and store it in the next variable
      sum += next; // Add the temperature to the sum variable
    }

    double average = sum / numDays; // Calculate the average temperature by dividing the sum by the number of days
    System.out.println(); // Print an empty line
    System.out.println("Average Temp: " + average); // Display the average temperature to the console
  }
}

```

{% endcode %}

### **Find the Days Above Average Temperature**

```java
import java.util.*;

class Main {
  public static void main(String[] args) {
    Scanner console = new Scanner(System.in); // Create a Scanner object to read user input
    System.out.print("How many days' temperature?"); // Prompt the user to enter the number of days
    int numDays = console.nextInt(); // Read the number of days entered by the user and store it in the numDays variable

    int[] temps = new int[numDays]; // Create an array to store the temperatures, with size equal to the number of days
    int sum = 0; // Initialize a variable to store the sum of temperatures
    for (int i=0; i<numDays; i++) { // Start a loop from 1 to numDays (inclusive)
      System.out.print("Day " + (i+1) + "'s high temp: "); // Prompt the user to enter the high temperature for each day
      temps[i] = console.nextInt(); // Read the temperature entered by the user and store it in the corresponding index of the temps array
      sum += temps[i]; // Add the temperature to the sum variable
    }

    double average = sum / numDays; // Calculate the average temperature by dividing the sum by the number of days

    // Count days above average
    int above = 0; // Initialize a variable to store the count of days above average
    for(int i=0; i<temps.length;i++) { // Start a loop from 0 to the length of the temps array (exclusive)
      if(temps[i]>average) { // Check if the temperature at the current index is greater than the average
        above++; // Increment the above variable if the temperature is above average
      }
    }

    System.out.println(); // Print an empty line
    System.out.println("Average Temp: " + average); // Display the average temperature to the console
    System.out.println(above + " days above average"); // Display the count of days above average to the console
  }
}
```

Output:

```java
How many days' temperature? 2
Day 1's high temp: 10
Day 2's high temp: 20

Average Temp: 15.0
1 days above average
```

***

## Leetcode Question: Middle Function

Write a function called middle that takes an array and returns a new array that contains all but the first and last elements.

`1. myArray = [1, 2, 3, 4] 2. middle(myArray) # [2,3]`

Solution: With While Loop

```java
public class Exercise {
    public static int[] middle(int[] array) {
        if (array.length <= 2) {
            return new int[0]; // Return an empty array if the input array has 2 or fewer elements
        }

        // Create a new array with a size of the input array length minus 2
        int[] middleArray = new int[array.length - 2];

        // Copy the elements from the input array, excluding the first and last elements
        int index = 1; // Start index at 1 to skip the first element
        while (index < array.length - 1) {
            middleArray[index - 1] = array[index]; // Copy the element from the input array to the corresponding index in the middleArray
            index++; // Move to the next element in the input array
        }

        return middleArray; // Return the new array containing the middle elements
    }
}

```

Here's the line-by-line explanation:

1. We define a public class named `Exercise`.
2. Inside the class, we declare a public static method named `middle`, which takes an integer array as input and returns an integer array.
3. We check if the length of the input array is less than or equal to 2 using `array.length <= 2`. If this condition is true, we return a new empty integer array `new int[0]` because there are no middle elements to extract.
4. If the condition in the previous step is false, we proceed to create a new integer array called `middleArray` with a size equal to the length of the input array minus 2.
5. We declare an integer variable `index` and initialize it to 1. This variable is used to keep track of the index while copying elements from the input array to the `middleArray`.
6. We enter a `while` loop that continues as long as `index` is less than the length of the input array minus 1. This loop skips the first and last elements of the input array.
7. Inside the loop, we assign the value of `array[index]` to the corresponding index in the `middleArray`. Since we start copying from the second element of the input array, we subtract 1 from `index` to get the correct index in the `middleArray`.
8. After copying the element, we increment the `index` variable to move to the next element in the input array.
9. Once the loop finishes, we have copied all the middle elements from the input array to the `middleArray`.
10. Finally, we return the `middleArray` from the `middle` method.

In summary, the `middle` method takes an input array and returns a new array containing the middle elements. If the input array has 2 or fewer elements, an empty array is returned. Otherwise, the middle elements are copied from the input array to a new array, excluding the first and last elements.

Solution: With For Loop

```java

public class Exercise {
    public static int[] middle(int[] array) {
        if (array.length <= 2) {
            return new int[0]; // Return an empty array if the input array has 2 or fewer elements
        }

        // Create a new array with a size of the input array length minus 2
        int[] middleArray = new int[array.length - 2];

        // Copy the elements from the input array, excluding the first and last elements
        for (int i = 1; i < array.length - 1; i++) {
            middleArray[i - 1] = array[i]; // Copy the element from the input array to the corresponding index in the middleArray
        }

        return middleArray; // Return the new array containing the middle elements
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int[] middleArr = middle(arr);
        System.out.println(Arrays.toString(middleArr));
    }
}
```

Visualization:

{% embed url="<https://cscircles.cemc.uwaterloo.ca/java_visualize/#mode=display>" %}

***

## Leetcode Question: Sum of Diagonal Elements

Given 2D array calculate the sum of diagonal elements.

**Example**

`1. myArray2D= {{1,2,3},{4,5,6},{7,8,9}}; 2.   3. sumDiagonalElements(myArray2D) # 15`

Solution:

```java

import java.util.Arrays;  // Importing the java.util package which includes the Arrays class

public class Exercise {
    public static int sumDiagonalElements(int[][] array) {
        int sum = 0;  // Variable to store the sum of diagonal elements
        int numRows = array.length;  // Number of rows in the 2D array

        for (int i = 0; i < numRows; i++) {  // Loop through each row
            sum += array[i][i];  // Add the diagonal element at position (i, i) to the sum
        }

        return sum;  // Return the sum of diagonal elements
    }

    public static void main(String[] args) {
        // Test the sumDiagonalElements method

        int[][] array = {
            {1, 2, 3},  // First row of the 2D array
            {4, 5, 6},  // Second row of the 2D array
            {7, 8, 9}   // Third row of the 2D array
        };

        int result = sumDiagonalElements(array);  // Calculate the sum of diagonal elements
        System.out.println("Sum of diagonal elements: " + result);  // Print the result
    }
}
```

Explanation:

1. The `sumDiagonalElements` method takes a 2D array (`int[][] array`) as input and returns an integer, which is the sum of the diagonal elements in the array.
2. It initializes a variable `sum` to 0, which will store the sum of the diagonal elements.
3. It determines the number of rows in the array by accessing the `length` property of the `array` variable. This is done using `int numRows = array.length`.
4. The method then enters a loop that iterates from 0 to `numRows - 1`. This loop is responsible for summing the diagonal elements.
5. Within the loop, the code adds the value of the current diagonal element (`array[i][i]`) to the `sum` variable.
6. Once the loop finishes, the method returns the `sum` of the diagonal elements.

In the `main` method:

1. An example 2D array (`int[][] array`) is created and initialized with values.
2. The `sumDiagonalElements` method is called, passing the `array` as an argument.
3. The returned sum of the diagonal elements is stored in the `result` variable.
4. Finally, the result is printed to the console using `System.out.println`.

**The key parts of the code are the iteration through the diagonal elements using the `for` loop and the summing of the diagonal elements within that loop. By accessing `array[i][i]`, we are accessing the diagonal elements with the same row and column index. The sum of these elements is then returned and printed.**

Why not numColumns?

That's a great question! The reason we're using `numRows` instead of `numColumns` is because we're interested in adding up the diagonal elements of the matrix, which are the elements that lie on the diagonal line that goes from the top left corner to the bottom right corner of the matrix.

Since the diagonal line of a matrix always has the same number of elements as the number of rows in the matrix, we only need to iterate through the rows of the matrix to add up the diagonal elements. That's why we're using `numRows` as the limit of our for loop, rather than `numColumns`.

If we were interested in adding up the elements on the other diagonal line of the matrix (i.e., the one that goes from the top right corner to the bottom left corner), we would need to iterate through the columns of the matrix and use `numColumns` instead of `numRows`.

In summary, the variable `numRows` is used in this code because we're calculating the sum of the diagonal elements of the matrix, which are always located on the diagonal line from the top left to the bottom right, and this diagonal line always has the same number of elements as the number of rows in the matrix.

Visualization:

{% embed url="<https://cscircles.cemc.uwaterloo.ca/java_visualize/#code=import+java.util.Arrays%3B%0A%0Apublic+class+Exercise+%7B%0A++++public+static+int+sumDiagonalElements(int%5B%5D%5B%5D+array)+%7B%0A++++++++int+sum+%3D+0%3B%0A++++++++int+numRows+%3D+array.length%3B%0A%0A++++++++for+(int+i+%3D+0%3B+i+%3C+numRows%3B+i%2B%2B)+%7B%0A++++++++++++sum+%2B%3D+array%5Bi%5D%5Bi%5D%3B%0A++++++++%7D%0A%0A++++++++return+sum%3B%0A++++%7D%0A%0A++++public+static+void+main(String%5B%5D+args)+%7B%0A++++++++//+Test+the+sumDiagonalElements+method%0A++++++++int%5B%5D%5B%5D+array+%3D+%7B%0A++++++++++++%7B1,+2,+3%7D,%0A++++++++++++%7B4,+5,+6%7D,%0A++++++++++++%7B7,+8,+9%7D%0A++++++++%7D%3B%0A++++++++int+result+%3D+sumDiagonalElements(array)%3B%0A++++++++System.out.println(%22Sum+of+diagonal+elements%3A+%22+%2B+result)%3B%0A++++%7D%0A%7D%0A&mode=display&curInstr=0>" %}

***

## Leetcode Question: Best Score

Given an array, write a function to get first, second best scores from the array and return it in new array. Array may contain duplicates.

**Example**

`1. myArray = {84,85,86,87,85,90,85,83,23,45,84,1,2,0} 2. firstSecond(myArray) // {90, 87}`

Solution:

```java

import java.util.Arrays;  // 📚 Importing the Arrays class from the java.util package
import java.util.Collections;  // 📚 Importing the Collections class from the java.util package

public class Exercise {
    public static int[] findTopTwoScores(int[] array) {
        int firstHighest = Integer.MIN_VALUE;  // 🏆 Variable to store the highest score, initially set to the smallest possible integer value
        int secondHighest = Integer.MIN_VALUE;  // 🥈 Variable to store the second highest score, initially set to the smallest possible integer value

        for (int score : array) {  // 🔄 Iterate over each score in the array
            if (score > firstHighest) {  // 🆙 If the current score is higher than the highest score
                secondHighest = firstHighest;  // 🔄 Move the previous highest score to the second highest variable
                firstHighest = score;  // 🔝 Update the highest score to the current score
            } else if (score > secondHighest && score < firstHighest) {  // 🆙 If the current score is higher than the second highest score but lower than the highest score
                secondHighest = score;  // 🔄 Update the second highest score to the current score
            }
        }

        return new int[]{firstHighest, secondHighest};  // 🔝🥈 Create and return an array containing the highest and second highest scores
    }

    public static void main(String[] args) {
         int[] scores = {84,85,86,87,85,90,85,83,23,45,84,1,2,0};  // 📈 Create an array of scores
         int[] topTwo = findTopTwoScores(scores);  // 🔝🥈 Find the top two scores
         System.out.println("The top two scores are: " + topTwo[0] + " and " + topTwo[1]);  // 📊 Print out the top two scores
    }
}
```

Explanation:

The key parts of the code are as follows:

1. `int firstHighest = Integer.MIN_VALUE;` and `int secondHighest = Integer.MIN_VALUE;` - These variables are used to track the highest and second highest scores. They are initially set to the smallest possible integer value (`Integer.MIN_VALUE`).
2. The `for` loop `for (int score : array)` - This loop iterates over each element in the `array` of scores. It uses an enhanced for loop syntax to assign each score to the variable `score`.
3. The conditional statements inside the loop - These statements compare the current `score` with the highest and second highest scores obtained so far, updating the variables accordingly. If the `score` is higher than the `firstHighest`, it becomes the new `firstHighest`, and the previous `firstHighest` is moved to `secondHighest`. If the `score` is higher than the `secondHighest` but lower than the `firstHighest`, it becomes the new `secondHighest`.
4. `return new int[]{firstHighest, secondHighest};` - This line creates a new array containing the highest and second highest scores and returns it as the result.
5. The `main` method - This method is used to test the `findTopTwoScores` method. It creates an array of test scores, calls the `findTopTwoScores` method with the scores array, and prints the original scores array and the top two scores array for verification.
6. **`public static int[] findTopTwoScores(int[] array) {`**: Time complexity is O(1) as it defines the function.
7. **`int firstHighest = Integer.MIN_VALUE;`**: Time complexity is O(1) as it initializes the firstHighest variable.
8. **`int secondHighest = Integer.MIN_VALUE;`**: Time complexity is O(1) as it initializes the secondHighest variable.
9. **`for (int score : array) {`**: The time complexity of the loop itself is O(n) because it iterates through each element in the input array, where n is the number of elements. The loop's time complexity will be determined by the operations inside the loop.
10. **`if (score > firstHighest) {`**: Time complexity is O(1) as it performs a single comparison.
11. **`secondHighest = firstHighest;`**: Time complexity is O(1) as it performs a single assignment operation.
12. **`firstHighest = score;`**: Time complexity is O(1) as it performs a single assignment operation.
13. **`} else if (score > secondHighest && score < firstHighest) {`**: Time complexity is O(1) as it performs up to two comparisons.
14. **`secondHighest = score;`**: Time complexity is O(1) as it performs a single assignment operation.
15. **`}`**: Time complexity is O(1) as it closes the if-else statement.
16. **`}`**: Time complexity is O(1) as it closes the for-each loop.
17. **`return new int[]{firstHighest, secondHighest};`**: Time complexity is O(1) as it returns an integer array containing two elements.

In summary, the time complexity of the **`findTopTwoScores`** function is determined by the for-each loop, which has a time complexity of O(n), where n is the number of elements in the input array. Since the operations inside the loop also have a time complexity of O(1), the overall time complexity of the **`findTopTwoScores`** function is O(n).

Visualization:

***


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://qatesting.gitbook.io/qa/java/data-structures-+-algorithms/data-structures/array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
