Basic Arrays
Sum of Array Elements
class Solution {
public int sum(int arr[], int n) {
int sum = 0;
for (var x : arr)
sum += x;
return sum;
}
}The algorithm iterates through each element of the array and adds its value to a running sum.
Time Complexity: O(n), where n is the number of elements in the array, as it traverses the array once.
Space Complexity: O(1).
Count of odd numbers in array
class Solution{
public int countOdd(int[] arr, int n) {
int countOdd = 0;
for (var x : arr) {
if (x % 2 == 1) ++countOdd;
}
return countOdd;
}
}This code iterates through the array, checking if each element is odd using the modulo operator. It increments a counter for each odd number found.
Time Complexity: O(n), as it loops through the entire array.
Space Complexity: O(1).
Check if the Array is Sorted I
class Solution {
boolean arraySortedOrNot(int[] arr, int n) {
boolean flag = true;
for (int i = 1; i < n; ++i) {
if (arr[i - 1] > arr[i]) return false;
}
return true;
}
}The algorithm checks if the array is sorted in non-decreasing order. It iterates from the second element, comparing each element with the one before it. If it finds any pair of adjacent elements in the wrong order, it immediately returns false.
Time Complexity: O(n), as in the worst case it will scan the entire array.
Space Complexity: O(1).
Reverse an array
class Solution {
public void reverse(int[] arr, int n) {
for (int i = 0, j = n - 1; i < j; ++i, --j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return;
}
}This method reverses the array in-place using a two-pointer technique. One pointer (i) starts from the beginning and another (j) from the end. The elements at these pointers are swapped, and the pointers are moved towards the center until they meet or cross.
Time Complexity: O(n), as it performs n/2 swaps.
Space Complexity: O(1), because the reversal is done in-place.