🔸Array
What is an Array?
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.
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.
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.
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:
Declare: This step involves creating a reference to the array, specifying its type and name.
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.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:
Insertion in 1D Array
Example:
Explanation:
This line declares a public class named SingleDimensionArray
. A class serves as a blueprint for creating objects with specific properties and behaviors.
This line declares an integer array variable named arr
and initializes it with a null value. It indicates that the array is currently empty.
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.
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.
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.
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.
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.
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.
This line assigns the valueToBeInserted
to the element at the specified location
in the arr
array.
This line prints the message "Successfully inserted" to the console, indicating that the value has been successfully inserted at the specified location.
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.
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.
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.
This line marks the end of the insert
method.
This line marks the end of the `SingleDimensionArray' class.
Let's analyze the code and the output it produces when executed:
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.
sda.insert(0, 0);
This inserts the value
0
at index0
.
sda.insert(1, 10);
This inserts the value
10
at index1
.
sda.insert(2, 20);
This inserts the value
20
at index2
.
sda.insert(1, 30);
This attempts to insert the value
30
at index1
, but since that index is already occupied, it will display a message indicating that the cell is already occupied.
sda.insert(12, 120);
This attempts to insert the value
120
at index12
, 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:
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.
The time complexity of a try-catch block is typically considered to be constant time, O(1).
Access 1D Element
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:
sda.insert(0, 10);
This inserts the value
10
at index0
.
sda.insert(1, 20);
This inserts the value
20
at index1
.
sda.insert(2, 30);
This inserts the value
30
at index2
.
After the insertions, we access the elements of the arr
array using index access:
var firstElement = sda.arr[0];
This assigns the value of the first element of the
arr
array (10
) to thefirstElement
variable.
System.out.println(firstElement);
This prints the value of
firstElement
to the console, which is10
.
var thirdElement = sda.arr[2];
This assigns the value of the third element of the
arr
array (30
) to thethirdElement
variable.
System.out.println(thirdElement);
This prints the value of
thirdElement
to the console, which is30
.
Now let's analyze the expected output:
When the code runs, it will print the corresponding values of the firstElement
and thirdElement
variables, which are 10
and 30
, respectively.
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.
Traverse 1D Array
Let's analyze the code and the output it produces:
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
objectsda
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:
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 isInteger.MIN_VALUE
(-2147483648 in this case). Therefore, the output is "0 10 20 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648 -2147483648".
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.
Finding Array Element (Linear Search
)
Linear Search
)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
objectsda
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:
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.
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.
Delete an Element
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:
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 beInteger.MIN_VALUE
since the value at index 0 was deleted.
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.
Time and Space Complexity of 1D Arrays
Operation | Time Complexity | Space Complexity |
---|---|---|
Creating an empty array | O(1) | O(n) |
Inserting a value in an array | O(1) | O(1) |
Traversing a given array | O(n) | O(1) |
Accessing a given cell | O(1) | O(1) |
Searching a given value | O(n) | O(1) |
Deleting a given value | O(1) | O(1) |
Create 2D Array
The provided code demonstrates the declaration, instantiation, initialization, and printing of a two-dimensional array in Java.
Here's a breakdown of the code:
Declaration:
This line declares a variable
int2dArray
of typeint[][]
, which represents a two-dimensional array of integers.Instantiation:
This line creates a new two-dimensional integer array with a size of 2x2. It assigns the newly created array to the
int2dArray
variable.Initialization:
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.Printing the Array:
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 theint2dArray
in the format [[1, 2], [3, 4]].Creating and Printing a String 2D Array:
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 ofs2dArray
usingArrays.deepToString()
.
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.
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:
Class Definition:
The
TwoDimensionalArray
class contains the definition of the array and theinsertValueInTheArray()
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 toInteger.MIN_VALUE
as a default value.Main Method:
In the
main
method, an instance ofTwoDimensionalArray
is created with 3 rows and 3 columns. TheinsertValueInTheArray()
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:
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).
⏱️ 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).
Access 2D Element
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:
The output of this code should be:
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.
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.
Traverse a 2D Array
Main Method:
The output of the given Java program would be:
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.
Finding 2D Array Element
Main Method:
Output:
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.
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:
The method is defined as
public
, which means it can be accessed from other parts of the program.The method has a loop that iterates through each row of a two-dimensional array called
arr
. The loop initializes a variablerow
to 0, and as long asrow
is less than the length ofarr
, the loop continues. After each iteration, therow
variable is incremented by 1.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 ascol
is less than the length of the first row ofarr
(assuming that all rows have the same length), the loop continues. After each iteration, thecol
variable is incremented by 1.Within the inner loop, there is an
if
statement that checks if the current element inarr
(at therow
andcol
indices) is equal to thevalue
passed to the method. If there is a match, it means the desired value has been found.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
andcol
concatenated with the appropriate strings. After printing the message, thereturn
statement is used to exit the method, as there is no need to continue searching.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
Main Method:
Output:
The time complexity is O(1) because we are printing a message to the console.
Explanation:
The method is declared as
public
, indicating it can be accessed from other parts of the program. It takes two integer parameters,row
andcol
, representing the row and column indices of a two-dimensional array.The method tries to perform the deletion of a value at the specified
row
andcol
indices. It does this by assigningInteger.MIN_VALUE
(the minimum possible integer value in Java) to the element atarr[row][col]
. This effectively marks the value as deleted or removed from the array.The
try
block is used to encapsulate the code that might throw anArrayIndexOutOfBoundsException
. This exception occurs when the provided indices are outside the valid range for the array.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 fromarr[row][col]
.If an
ArrayIndexOutOfBoundsException
occurs, the code inside the correspondingcatch
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
Operation | Time Complexity | Space Complexity |
---|---|---|
Creating an empty array | O(1) | O(mn) |
Inserting a value in an array | O(1) | O(1) |
Traversing a given array | O(mn) | O(1) |
Accessing a given cell | O(1) | O(1) |
Searching a given value | O(mn) | O(1) |
Deleting a given value | O(1) | O(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.
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.
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.
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.
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.
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.
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.
Array Project
Calculate Average Temperature
Find the Days Above Average Temperature
Output:
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
Here's the line-by-line explanation:
We define a public class named
Exercise
.Inside the class, we declare a public static method named
middle
, which takes an integer array as input and returns an integer array.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 arraynew int[0]
because there are no middle elements to extract.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.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 themiddleArray
.We enter a
while
loop that continues as long asindex
is less than the length of the input array minus 1. This loop skips the first and last elements of the input array.Inside the loop, we assign the value of
array[index]
to the corresponding index in themiddleArray
. Since we start copying from the second element of the input array, we subtract 1 fromindex
to get the correct index in themiddleArray
.After copying the element, we increment the
index
variable to move to the next element in the input array.Once the loop finishes, we have copied all the middle elements from the input array to the
middleArray
.Finally, we return the
middleArray
from themiddle
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
Visualization:
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:
Explanation:
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.It initializes a variable
sum
to 0, which will store the sum of the diagonal elements.It determines the number of rows in the array by accessing the
length
property of thearray
variable. This is done usingint numRows = array.length
.The method then enters a loop that iterates from 0 to
numRows - 1
. This loop is responsible for summing the diagonal elements.Within the loop, the code adds the value of the current diagonal element (
array[i][i]
) to thesum
variable.Once the loop finishes, the method returns the
sum
of the diagonal elements.
In the main
method:
An example 2D array (
int[][] array
) is created and initialized with values.The
sumDiagonalElements
method is called, passing thearray
as an argument.The returned sum of the diagonal elements is stored in the
result
variable.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:
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:
Explanation:
The key parts of the code are as follows:
int firstHighest = Integer.MIN_VALUE;
andint 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
).The
for
loopfor (int score : array)
- This loop iterates over each element in thearray
of scores. It uses an enhanced for loop syntax to assign each score to the variablescore
.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 thescore
is higher than thefirstHighest
, it becomes the newfirstHighest
, and the previousfirstHighest
is moved tosecondHighest
. If thescore
is higher than thesecondHighest
but lower than thefirstHighest
, it becomes the newsecondHighest
.return new int[]{firstHighest, secondHighest};
- This line creates a new array containing the highest and second highest scores and returns it as the result.The
main
method - This method is used to test thefindTopTwoScores
method. It creates an array of test scores, calls thefindTopTwoScores
method with the scores array, and prints the original scores array and the top two scores array for verification.public static int[] findTopTwoScores(int[] array) {
: Time complexity is O(1) as it defines the function.int firstHighest = Integer.MIN_VALUE;
: Time complexity is O(1) as it initializes the firstHighest variable.int secondHighest = Integer.MIN_VALUE;
: Time complexity is O(1) as it initializes the secondHighest variable.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.if (score > firstHighest) {
: Time complexity is O(1) as it performs a single comparison.secondHighest = firstHighest;
: Time complexity is O(1) as it performs a single assignment operation.firstHighest = score;
: Time complexity is O(1) as it performs a single assignment operation.} else if (score > secondHighest && score < firstHighest) {
: Time complexity is O(1) as it performs up to two comparisons.secondHighest = score;
: Time complexity is O(1) as it performs a single assignment operation.}
: Time complexity is O(1) as it closes the if-else statement.}
: Time complexity is O(1) as it closes the for-each loop.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:
Last updated