ADSA Assignment 1
ADSA Assignment 1
Vansh Agarwal
Section-19 (22SCSE1010944)
Program:
public class ArrayProblems {
public static int findLargest(int[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
}
Time Complexity: O(n)
Space Complexity: O(1)
Algorithm:
1. Initialize two pointers: one at the start and one at the end of
the array.
2. Swap the elements at these pointers.
3. Move the start pointer forward and the end pointer backward.
4. Repeat until the pointers meet.
Program
public class ArrayProblems {
public static void reverseArray(int[] arr) {
int start = 0, end = arr.length - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}
Time Complexity: O(n)
Space Complexity: O(1)
Program
public class ArrayProblems {
public static int findSecondLargest(int[] arr) {
if (arr.length < 2) {
throw new IllegalArgumentException("Array must
contain at least two elements");
}
int first = Integer.MIN_VALUE, second =
Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
second = first;
first = num;
} else if (num > second && num < first) {
second = num;
}
}
if (second == Integer.MIN_VALUE) {
throw new IllegalArgumentException("No second largest
element found");
}
return second;
}
}
Time Complexity: O(n)
Space Complexity: O(1)
Algorithm:
1. Traverse through the array and check if each element is less
than or equal to the next one.
Program
Algorithm:
1. Use a HashSet to keep track of seen elements.
2. Traverse the array and add only unseen elements to a new list.
Program
import java.util.HashSet;
import java.util.ArrayList;
Algorithm:
1. Use array slicing to rotate the array. For example, to rotate right
by k positions.
Program:
public class ArrayProblems {
public static void rotateArray(int[] arr, int k) {
int n = arr.length;
k %= n; // In case k is greater than array length
reverse(arr, 0, n - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, n - 1);
}
Program
import java.util.HashMap;