Array Tasks Easy Level
Array Tasks Easy Level
📌 What is an Array?
An array is a fixed-size collection of elements of the same data
type, stored in contiguous memory locations. It allows efficient
access to elements using an index.
Easy 1
Level
int[] arr = 10, 20, 30, 40, 50; // Array with 5 elements
✅ Output:
First Element: 10
Third Element: 30
Last Element: 50
Easy 2
Level
}
✅ Output:
Student 1 Marks: 85
Student 2 Marks: 90
Student 3 Marks: 78
Student 4 Marks: 92
Student 5 Marks: 88
🔹 Conclusion
✅ Arrays provide a structured way to store multiple values of the same
type.
✅ They allow fast access using indexes but have a fixed size.
✅ Arrays are widely used in programming for storing and processing
data efficiently.
Easy 3
Level
Declaration Only
int[] arr;
arr = new int[5]; // Allocating space for 5 elements
Easy 4
Level
✅ Double Array
✅ Character Array
✅ Boolean Array
🔹 Printing an Array
✅ Using a Loop
✅ Output:
Easy 5
Level
}
Array elements: 10 20 30 40 50
}
🔹 Summary Table
Method Syntax Use Case
Declaration Only int[] arr; When size/values are
unknown
Declaration + int[] arr = new int[5]; Fixed size, unknown values
Initialization
Direct Initialization int[] arr = 10, 20, 30; Values are known in advance
new with Values int[] arr = new int[]{1, 2, 3; Alternative initialization
Printing for (int i 0; i < arr.length; i+ Accessing array elements
+)
public class
Easy SplitArray { 6
Level
// Method to split the array into two halves
for (int i 0; i < mid; i+
+) { firstHalf[i] =
arr[i];
}
✅ Output:
Easy 1
Level 0
First Half: 10 20 30 40
Second Half: 50 60 70
copying logic
public class
SplitArrayOptimized {
Easy 12
Level
System.out.print(num +
" ");
}
} System.out.println();
✅ Output:
First Half: 5 15 25 35
Second Half: 45 55 65 75
5, 15, 25, 35, 45, 55, 65, 5, 15, 25, 35 45, 55, 65, 75
75
1, 2, 3, 4, 5 1, 2, 3 4, 5
value.
Easy 13
Level
🔹 Implementation
public class UpdateArrayElement {
Easy 14
Level
updateElement(arr, 2,
} 99);
}
✅ Output:
Original Array: 10 20 30 40 50
Updated Array: 10 20 99 40 50
🔹 Implementation
public class UpdateMultipleElements {
Easy 15
Level
// Print updated array
System.out.print("Updated Array: ");
printArray(arr);
}
✅ Output:
Original Array: 5 10 15 20 25
Updated Array: 5 99 15 88 25
Easy 15
Level
🔹 Sample Inputs & Expected Outputs
Input Array Index to Update New Value Updated Array
10, 20, 30, 40, 50 2 99 10, 20, 99, 40, 50
5, 10, 15, 20, 25 1, 3 99, 88 5, 99, 15, 88, 25
🔹 Implementation
public class
LinearSearch {
// Method to perform Linear Search
public static int findElement(int[] arr, int
target) { for (int i 0; i < arr.length; i++)
{
if (arr[i] == target) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
Easy 16
Level
public static void main(String[]
args) { int[] arr = 15, 28, 37,
44, 59;
✅ Output:
🔹 Implementation
public class
LinearSearchMultiple {
// Method to find all occurrences of an element
public static void findAllOccurrences(int[] arr, int
target) { boolean found = false;
System.out.print("Element " + target + " found at
index: ");
Easy 17
Level
System.out.print(i + "
");
} found = true;
}
if (!found) {
System.out.println("Element " + target + " not found in the
array.");
} else {
System.out.println();
} }
findAllOccurrences(arr,
} target);
}
✅ Output:
Easy 1
Level 8
🔹 Approach 1: Simple Iteration (Brute Force)
Iterate through the array.
count.
🔹 Implementation
public class
CountOccurrences {
// Method to count occurrences of a target
element public static int countOccurrences(int[]
arr, int target) {
int count 0;
for (int num : arr) {
if (num == target) {
count++;
}
}
return count;
}
Easy 1
Level 9
🔹 Approach 2: Using a Frequency Array (for
Small Fixed Range)
If the range of elements is small (e.g.,0- ), we can use an auxiliary array
100
( freq[] ) to store the count of each element.
🔹 Implementation
public class CountOccurrencesWithFrequencyArray {
✅ Output:
Easy 2
Level 0
🔹 Approach 3: Sorted Array - Optimized using
Binary Search
If the array is sorted, we can use Binary Search to find the
first and last occurrence of the element.
🔹 Implementation
public class
CountOccurrencesBinarySearch {
// Binary Search to find the first occurrence of
target public static int firstOccurrence(int[] arr, int
target) {
int low 0, high = arr.length - 1, first = -1;
while (low <= high) {
int mid = (low + high) /
2; if (arr[mid] ==
target) {
first = mid;
high = mid - 1; // Move left to find first
occurrence
} else if (arr[mid] < target)
{ low = mid + 1;
} else {
high = mid - 1;
}
}
Easy 21
Level
last = mid;
low = mid + 1; // Move right to find last
occurrence
} else if (arr[mid] < target)
{ low = mid + 1;
} else {
high = mid - 1;
}
}
return last;
}
Easy 22
Level
Input Array Target Output
Element (Occurrences)
10, 20, 10, 30, 10, 40, 10 4
10
5, 8, 5, 3, 5, 8, 8, 8 8 4
1, 2, 3, 3, 3, 4, 5, 6 3 3
2, 4, 6, 8, 10 7 0
📌 Key Takeaways
1. Brute Force: Simple iteration (Best for small/unsorted arrays). O(n)
Time Complexity:
O(n)O(n)
🔹 Implementation
public class
FirstLastOccurrence {
// Method to find first and last occurrence using
linear search public static void findOccurrences(int[]
arr, int target) {
// Display the
result if (first ==
-1)
System.out.println("Element " + target + " not found in the
array.");
} else {
t);
System.out.println("Last occurrence of " + target + " at index:
} " + last);
}
findOccurrences(arr,
} target);
}
✅ Output:
Easy 24
Level
Use Binary Search again to find the last
🔹 Implementation
public class FirstLastOccurrenceBinarySearch {
Easy 26
Level
} else if (arr[mid] <
target) { low = mid +
1;
} else {
high = mid - 1;
}
}
} return last;
Easy 27
Level
This reduces redundant traversal, improving efficiency.
🔹 Implementation
public class FirstLastOccurrenceSinglePass {
if (first == -1)
System.out.println("Element " + target + " not found.");
} else {
System.out.println("First occurrence of " + target + " at index: "
t); + firs
findOccurrences(arr, target);
}
}
✅ Output:
Easy 28
Level
First occurrence of 5 at index:
1 Last occurrence of 5 at
index: 5
5, 8, 5, 3, 5, 8, 8, 8 8 5 7
📌 Key Takeaways
1. Brute Force (Linear Search) O(n)O(n): Simple but slow for large
arrays.
false.
🔹 Implementation
Easy 28
Level
public class
ArrayContains {
// Method to check if an array contains the target
number public static boolean containsNumber(int[]
arr, int target) {
for (int num : arr) {
if (num == target) {
return true; // Number found
}
}
return false; // Number not found
}
public static void main(String[]
args) { int[] arr = 10, 20, 30,
40, 50;
Easy 29
Level
Time Complexity: (Faster for large arrays).
O(logn)O(\log n)
🔹 Implementation
public class ArrayContainsBinarySearch {
if (arr[mid] == target)
{ return true; //
Found
} else if (arr[mid] < target) {
low = mid + 1; // Search right
} else {
high = mid - 1; // Search left
}
}
return false; // Not found
}
if (containsNumber(arr, target)) {
System.out.println("The array contains the number " + target);
} else {
System.out.println("The array does not contain the number " +
target);
}
Easy 3
Level 0
}
}
✅ Output:
🔹 Implementation
public class ArrayContainsHashing {
Easy 31
Level
if (containsNumber(arr, target)) {
System.out.println("The array contains the number " + target);
} else {
System.out.println("The array does not contain the number " +
target);
} }
}
✅ Output:
📌 Key Takeaways
1. Brute Force (Linear Search) O(n)O(n): Simple but slow for large
arrays.
🔹 Implementation
public class
ArraySum {
// Method to calculate the sum of all elements in
an array public static int findSum(int[] arr) {
int sum 0;
for (int num : arr)
{ sum += num;
}
return sum;
}
Easy 33
Level
Base Case: If the array is empty, return
0 .
Time Complexity: .
O(n)O(n)
🔹 Implementation
public class
ArraySumRecursion {
// Recursive method to compute sum of array
elements public static int findSum(int[] arr) {
return findSumHelper(arr, 0);
}
Easy 34
Level
🔹 Approach 3: Using Divide & Conquer
Divide the array into two halves and sum them recursively.
Time Complexity: .
O(n)O(n)
🔹 Implementation
public class
ArraySumDivideConquer {
// Method to sum elements using divide & conquer
approach public static int findSum(int[] arr) {
return findSumHelper(arr, 0, arr.length - 1);
}
Easy 35
Level
✅ Output:
📌 Key Takeaways
1. Iterative Approach (Brute Force) O(n)O(n): Simple and effective.
Easy 36
Level
🔹 Implementation
public class ReverseArray {
left+
+;
right--
;
}
}
System.out.println("Original Array:");
printArray(arr);
Easy 37
Level
System.out.println("Reversed
Array:");
} printArray(arr);
}
✅ Output:
Original
Array: 1 2 3
45
Reversed
Array: 5 4 3 2
Time Complexity:
O(n)O(n)
🔹 Implementation
public class
ReverseArrayRecursion {
// Recursive method to reverse an array
public static void reverseArray(int[] arr, int left, int
right) { if (left >= right) {
return;
}
// Swap elements
int temp =
arr[left]; arr[left]
= arr[right];
arr[right] = temp;
Easy 3
Level 8
// Recursive call
reverseArray(arr, left + 1, right
} - 1);
Original Array:
10 20 30 40
50
Reversed
Array: 50 40
Easy 3
Level 9
🔹 Approach 3: Using XOR Swap (Without Temp
Variable)
Concept: a = a ^ , b=a^ , a=a^
b b b
Eliminates the need for a temp variable.
Time Complexity:
O(n)O(n)
Space Complexity:
O(1)O(1)
🔹 Implementation
public class
ReverseArrayXOR
// Method to reverse an array using XOR
swapping public static void
reverseArray(int[] arr) {
Easy 40
Level
public static void main(String[]
args) {
int[] arr = 8, 6, 4, 2, 0;
System.out.println("Original
Array:");
printArray(arr);
// Reverse the
array
reverseArray(arr);
System.out.println("Reversed
Array:");
} printArray(arr);
}
✅ Output:
Original
Array: 8 6 4
20
Reversed
Array: 0 2 4 6
📌 Key Takeaways
1. Two-Pointer Swap O(n)O(n): Best approach, simple and efficient.
Easy 41
Level
3. XOR Swap O(n)O(n): Avoids using a temp variable but is tricky.
🔹 Implementation
public class
ReverseArrayExtraSpace {
// Method to reverse an array using extra
space public static int[] reverseArray(int[]
arr) {
int n = arr.length;
Easy 42
Level
public static void main(String[]
args) {
int[] arr = 1, 2, 3, 4, 5;
System.out.println("Original
Array:");
printArray(arr);
// Reverse using extra space
int[] reversedArr =
reverseArray(arr);
System.out.println("Reversed
Array:");
} printArray(reversedArr);
}
✅ Output:
Original
Array: 1 2 3
45
Reversed
Array: 5 4 3 2
Time Complexity:
O(n)O(n)
🔹 Implementation
Easy 43
Level
import java.util.Stack;
return brr;
}
System.out.println("Original Array:");
printArray(arr);
Easy 44
Level
// Reverse using stack
int[] reversedArr =
reverseArray(arr);
System.out.println("Reversed
Array:");
} printArray(reversedArr);
}
✅ Output:
Original Array:
10 20 30 40
50
Reversed
Array: 50 40
Time Complexity:
O(n)O(n)
🔹 Implementation
public class
ReverseArrayRecursionExtraSpace {
// Recursive method to reverse an array into a new
array public static void reverseArray(int[] arr, int[]
brr, int index) {
if (index == arr.length) {
return;
}
Easy 45
Level
brr[arr.length - index - 1 arr[index]; // Copy in reverse
order
} reverseArray(arr, brr, index + 1);
Original
Array: 5 15
25 35 45
Reversed
Array: 45 35
Easy 46
Level
🔹 Sample Inputs & Expected Outputs
Input Array Output
(Reversed)
1, 2, 3, 4, 5 5, 4, 3, 2, 1
📌 Key Takeaways
1. Using a New Array O(n)O(n): Easiest method, straightforward.
3. Using Recursion O(n)O(n): Not optimal due to extra call stack space.
Time Complexity:
O(n)O(n)
Space Complexity:
O(1)O(1)
🔹 Implementation
public class
MinMaxArray {
// Method to find min and max in an
array public static void
findMinMax(int[] arr) {
Easy 47
Level
int max =
arr[0];
for (int i 1; i < arr.length; i+
+) { if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max)
{ max = arr[i];
}
}
findMinMax(arr
} );
}
✅ Output:
Given Array:
12 3 8 22 15
Minimum Value: 3
Maximum Value: 22
Easy 4
Level 8
🔹 Approach 2: Sorting and Picking First & Last
Elements
Sort the array in ascending order.
🔹 Implementation
public class
MinMaxSorting {
// Method to find min and max using
sorting public static void
findMinMax(int[] arr) {
// Sorting the array
for (int i 0; i < arr.length - 1; i++) {
for (int j 0; j < arr.length - i - 1; j+
+) { if (arr[j] > arr[j + 1)
int temp =
arr[j]; arr[j] =
arr[j + 1; arr[j +
1 temp;
}
}
Easy 4
Level 9
int[] arr = 25, 5, 18, 7,
30;
System.out.println("Given
Array:"); for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
findMinMax(arr
} );
}
✅ Output:
Given Array:
25 5 18 7 30
Minimum Value: 5
Maximum Value: 30
Time Complexity:
O(n)O(n)
🔹 Implementation
public class
MinMaxDivideConquer {
// Helper method to find min and
max
Easy 5
Level 0
public static void findMinMax(int[] arr, int left, int right, int[]
result) { if (left == right) { // Single element case
result[0] = arr[left]; //
min result[1] = arr[left];
// max return;
}
// Merge results
result[0] Math.min(leftResult[0],
rightResult[0]); result[1]
Math.max(leftResult[1], rightResult[1]);
}
System.out.println("Given
Easy 51
Level
Array:"); for (int num : arr) {
Easy 52
Level
System.out.print(num +
" ");
}
System.out.println();
int[] result = new int[2]; // [min,
max]
findMinMax(arr, 0, arr.length - 1,
System.out.println("Minimum Value: " +
result[0]);
} System.out.println("Maximum Value: " +
}
✅ Output:
Given Array:
45 7 12 90 23 8
Minimum Value: 7
Maximum Value: 90
📌 Key Takeaways
1. Brute Force O(n)O(n): Best for simple cases.
Easy 53
Level
Write a program to copy elements from one
array to another.
The goal is to copy elements from one brr
arr )
into ) without
array (
another ( using
built-in methods like
System.arraycopy( or Collections.
)
Time Complexity:
O(n)O(n)
🔹 Implementation
public class
ArrayCopy {
// Method to copy elements from one array to
another public static int[] copyArray(int[] arr) {
int n = arr.length;
int[] brr = new int[n];
✅ Output:
Original Array:
10 20 30 40
50
Copied Array:
10 20 30 40
Time Complexity:
O(n)O(n)
Space Complexity:
O(n)O(n)
🔹 Implementation
public class
ArrayCopyReverse {
// Method to copy elements in reverse
order
Easy 55
Level
public static int[] copyReverse(int[]
arr) { int n = arr.length;
int[] brr = new int[n];
int[] brr =
copyReverse(arr);
System.out.println("Reversed
Copy:"); for (int num : brr) {
System.out.print(num + " ");
}
}
}
✅ Output:
Original
Array: 5 10
15 20 25
Reversed
Copy: 25 20
Easy 55
Level
🔹 Approach 3: Copy Only Even Numbers
Copy only even numbers brr
from arr t (filtered copy).
o
Time Complexity:
O(n)O(n)
🔹 Implementation
public class
ArrayCopyEven {
// Method to copy only even numbers
public static int[] copyEvenNumbers(int[]
arr) { int count 0;
// Counting even
numbers for (int num :
arr) {
if (num % 2 0)
count++;
}
}
int[] brr = new
int[count];
int index 0;
// Copy only even
numbers for (int num :
arr) {
if (num % 2 0)
brr[index++] =
num;
}
} }
Easy 56
Level
public static void main(String[]
args) {
int[] arr = 4, 7, 12, 9, 16, 21;
System.out.println("Original
Array:"); for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
int[] brr =
copyEvenNumbers(arr);
System.out.println("Copied Even
Numbers:"); for (int num : brr) {
System.out.print(num + " ");
}
}
}
✅ Output:
Original Array:
4 7 12 9 16 21
Copied Even
Numbers: 4 12 16
5, 10, 15, 20, 25 5, 10, 15, 20, 25 25, 20, 15, 10, 5 10, 20
4, 7, 12, 9, 16, 21 4, 7, 12, 9, 16, 21 21, 16, 9, 12, 7, 4 4, 12, 16
Easy 57
Level
📌 Key Takeaways
1. Simple Copy O(n)O(n): t without modification.
Copies o
arr brr
2. Reverse Copy O(n)O(n): Copies elements in reverse order.
Time Complexity:
O(1)O(1)
Space Complexity:
O(1)O(1)
🔹 Implementation
public class
SwapFirstLast {
// Method to swap first and last elements
public static void swapUsingTemp(int[]
arr) {
if (arr.length 2)
return; // No need to swap if array has 0 or 1
elements
Easy 58
Level
arr[arr.length - 1 temp;
}
swapUsingTemp(ar
r);
System.out.println("After Swap:");
for (int num : arr) System.out.print(num +
} " ");
}
✅ Output:
Before Swap:
10 20 30 40 50
After Swap:
50 20 30 40 10
Time Complexity:
O(1)O(1)
Space Complexity:
O(1)O(1)
Note: This approach won't work if there are zeros in the array.
Easy 59
Level
🔹 Implementation
public class
SwapFirstLastMulDiv {
// Method to swap using multiplication and
division public static void swapUsingMulDiv(int[]
arr) {
if (arr.length 2 || arr[0] 0 || arr[arr.length - 1 0)
return;
}
arr[0] = arr[0] * arr[arr.length - 1;
arr[arr.length - 1 arr[0] / arr[arr.length -
1;
}
swapUsingMulDiv(ar
r);
System.out.println("After Swap:");
for (int num : arr) System.out.print(num +
} " ");
}
✅ Output:
Before
Swap: 2 4 6
8 10
After
Swap: 10
Easy 6
Level 0
🔹 Approach 3: Swapping Without a Temporary
Variable (Using Addition & Subtraction)
Uses arithmetic operations for swapping instead of a temporary
variable.
Time Complexity:
O(1)O(1)
Space Complexity:
O(1)O(1)
🔹 Implementation
public class
SwapFirstLastAddSub {
// Method to swap using addition and
subtraction public static void
swapUsingAddSub(int[] arr) {
if (arr.length 2)
return;
}
arr[0] = arr[0] + arr[arr.length - 1;
arr[arr.length - 1 arr[0] - arr[arr.length -
1;
}
swapUsingAddSub(arr)
;
Easy 61
Level
System.out.println("After Swap:");
for (int num : arr) System.out.print(num +
} " ");
}
✅ Output:
Before
Swap: 5 10
15 20 25
After Swap:
25 10 15 20
Time Complexity:
O(1)O(1)
Space Complexity:
O(1)O(1)
🔹 Implementation
public class
SwapFirstLastXOR
// Method to swap using XOR
public static void swapUsingXOR(int[]
arr) { if (arr.length 2)
return;
}
Easy 62
Level
arr[arr.length - 1 arr[0] ^ arr[arr.length -
1;
} arr[0] = arr[0] ^ arr[arr.length - 1;
swapUsingXOR(arr
);
System.out.println("After Swap:");
for (int num : arr) System.out.print(num +
} " ");
}
✅ Output:
Before
Swap: 3 6 9
12 15
After
Swap: 15
Easy 63
Level
📌 Key Takeaways
1. Basic Swap (O(1)): Uses a temporary variable.
4. XOR Swap (O(1)): Avoids extra space, works well in all cases.
Time Complexity:
O(n)O(n)
Space Complexity:
O(1)O(1)
🔹 Implementation
public class
LeftRotateByOne {
// Method to rotate left by one using a temporary
variable public static void leftRotateByOne(int[] arr) {
if (arr.length 2)
return; // No rotation needed for an empty or single-
element array
}
Easy 64
Level
for (int i 0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1; // Shift
elements left
}
}
leftRotateByOne(ar
r);
System.out.println("After Rotation:");
for (int num : arr) System.out.print(num +
} " ");
}
✅ Output:
Before
Rotation: 1 2
345
After
Rotation: 2 3
Time Complexity:
O(n)O(n)
Space Complexity:
Easy 65
Level
O(1)O(1)
🔹 Implementation
public class LeftRotateSwap {
System.out.println("Before Rotation:");
for (int num : arr) System.out.print(num +
" "); System.out.println();
leftRotateByOneSwap(arr);
System.out.println("After Rotation:");
for (int num : arr) System.out.print(num + " ");
}
}
✅ Output:
Easy 66
Level
Before
Rotation: 10
20 30 40 50
After
Rotation: 20
Steps:
Time Complexity:
O(n)O(n)
Space Complexity:
O(1)O(1)
🔹 Implementation
public class
LeftRotateReversal {
// Reverse a part of the array
private static void reverse(int[] arr, int start,
int end) { while (start < end) {
int temp =
arr[start];
arr[start] =
arr[end]; arr[end]
= temp;
start+
+;
end--;
Easy 67
Level
// Rotate left by one using reversal algorithm
public static void leftRotateByOneReversal(int[]
arr) { if (arr.length 2)
return;
}
System.out.println("Before Rotation:");
for (int num : arr) System.out.print(num +
" "); System.out.println();
leftRotateByOneReversal(arr);
System.out.println("After Rotation:");
for (int num : arr) System.out.print(num + " ");
}
}
✅ Output:
Before
Rotation: 5 10
15 20 25
After
Rotation: 10
Easy 6
Level 8
Input Array After Left
Rotation
1, 2, 3, 4, 5 2, 3, 4, 5, 1
10, 20, 30, 40, 50 20, 30, 40, 50, 10
📌 Key Takeaways
1. Brute Force Approach (O(n)): Uses a temporary variable for storing
the first element.
Time Complexity:
O(n)O(n)
Space Complexity:
O(1)O(1)
🔹 Implementation
Easy 6
Level 9
public class
ArrayAverage {
// Method to calculate average
public static double findAverage(int[] arr) {
if (arr.length 0) return 0; // Handle empty array
case
int sum 0;
for (int num : arr)
{ sum += num;
}
return (double) sum / arr.length; // Cast to double for accurate
division
}
Time Complexity:
O(n)O(n)
Easy 70
Level
🔹 Implementation
public class ArrayAverageRecursive {
✅ Output:
Formula:
Easy 71
Level
average=∑i=1nxin\text{average} = \frac{\sum_{i=1}^{n} x_i}{n}
Time Complexity:
O(n)O(n)
Space Complexity:
O(1)O(1)
🔹 Implementation
public class
ArrayAverageOptimized {
// Method to calculate average iteratively
public static double findAverageOptimized(int[]
arr) { if (arr.length 0) return 0;
double average 0;
for (int i 0; i < arr.length; i++) {
average = ((average * i) + arr[i]) / (i
+ 1);
}
} return average;
Easy 72
Level
Input Array Average
Output
10, 20, 30, 40, 50 30.0
1, 3, 5, 7, 9 5.0
📌 Key Takeaways
1. Brute Force Approach (O(n)) * Simple and efficient for most cases.
Space Complexity:
O(1)O(1)
🔹 Implementation
import
java.util.Arrays;
public class
SecondLargestSmallest {
Easy 73
Level
// Method to find second smallest and second largest using
sorting public static void findSecondLargestSmallest(int[]
arr) {
if (arr.length 2)
System.out.println("Array must have at least two
elements."); return;
}
arr[1];
int secondLargest = arr[arr.length - 2;
findSecondLargestSmallest(arr);
}
}
✅ Output:
Second Smallest: 7
Second Largest: 19
Easy 74
Level
2. Use two more variables for largest & second largest.
Easy 75
Level
Time Complexity:
O(n)O(n)
Space Complexity:
O(1)O(1)
🔹 Implementation
public class SecondLargestSmallestOptimized {
Easy 76
Level
}
}
Second Smallest: 7
Second Largest: 19
1, 2, 3, 4, 5 2 4
Easy 77
Level
📌 Key Takeaways
1. Sorting Approach (O(n log n)) * Easy to implement but inefficient
for large arrays.
class RemoveDuplicates {
// Method to remove duplicates using nested
loops public static int
removeDuplicatesBruteForce(int[] arr) {
int n = arr.length;
if (n 0 || n 1) return n; // Edge case: Empty or single element
Easy 77
Level
}
}
return newSize; // Return new array
} size
Easy 78
Level
for (int i 0; i < n - 1; i+
+) { if (arr[i] ! arr[i +
1)
arr[j++] = arr[i]; // Store unique
elements
}
}
Easy 79
Level
int j 0; // Pointer for unique
elements for (int i 1; i < n; i++) {
if (arr[i] ! arr[j])
{ j++;
arr[j] = arr[i]; // Store unique
element
}
}
return j + 1; // New size
}
✅ Summary of Approaches:
Time Space
Approach Best Use Case
Complexity Complexity
Small arrays,
Brute Force (Nested Loops) O(n2)O(n^2) O(1)O(1) simple
implementatio
n
O(nlogn)O(n When sorting
Sorting + Traversal O(1)O(1)
\log n) is allowed
Easy 8
Level 0
Sort an array in ascending order (without
using sorting functions).
Space
Complexity:
O(1)O(1)
Method: Repeatedly swaps adjacent elements if they are in the
wrong order.
class BubbleSort {
public static void bubbleSort(int[]
arr) { int n = arr.length;
for (int i 0; i < n - 1; i++) {
for (int j 0; j < n - i - 1; j+
+) { if (arr[j] > arr[j + 1)
// Swap arr[j] and arr[j +
1 int temp = arr[j];
arr[j] = arr[j + 1;
arr[j + 1 temp;
}
}
}
}
Space
Complexity:
O(1)O(1)
Space
Complexity:
O(1)O(1)
Method: Builds the sorted array one element at a time by shifting
elements.
class InsertionSort {
public static void insertionSort(int[]
arr) { int n = arr.length;
for (int i 1; i < n; i+
+) { int key =
arr[i];
int j = i - 1;
while (j 0 && arr[j] > key)
{ arr[j + 1 arr[j];
j--;
}
arr[j + 1 key;
}
}
Space
Complexity:
O(n)O(n)
Method: Divides the array into halves, sorts them, and merges them.
class MergeSort {
public static void mergeSort(int[] arr, int left, int
right) { if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
private static void merge(int[] arr, int left, int mid, int
right) { int n1 mid - left + 1;
int n2 right - mid;
1 + i];
int i 0, j 0, k = left;
while (i < n1 && j < n2)
if (leftArr[i] <= rightArr[j]) arr[k++] =
leftArr[i++]; else arr[k++] = rightArr[j++];
}
O(nlogn)O(n \
Merge Sort O(n)O(n) Large datasets, stable sorting
log n)
Easy 85
Level
Sort an array in descending order (without
using sorting functions).
Space
Complexity:
O(1)O(1)
Method: Repeatedly swaps adjacent elements if they are in the
wrong order.
class BubbleSortDescending {
public static void bubbleSortDescending(int[]
arr) { int n = arr.length;
for (int i 0; i < n - 1; i++) {
for (int j 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1) // Change > to < for descending
order int temp = arr[j];
arr[j] = arr[j + 1;
arr[j + 1 temp;
}
}
}
}
Easy 86
Level
}
}
Space
Complexity:
O(1)O(1)
Easy 87
Level
}
}
}
Space
Complexity:
O(1)O(1)
class InsertionSortDescending {
public static void insertionSortDescending(int[]
arr) { int n = arr.length;
for (int i 1; i < n; i+
+) { int key =
arr[i];
int j = i - 1;
while (j 0 && arr[j] < key) { // Change > to < for descending
order arr[j + 1 arr[j];
j--;
}
arr[j + 1 key;
}
}
Easy 8
Level 8
}
}
Space
Complexity:
O(n)O(n)
Method: Divides the array into halves, sorts them, and merges them.
class MergeSortDescending {
public static void mergeSortDescending(int[] arr, int left, int
right) { if (left < right) {
int mid = left + (right - left) / 2;
mergeSortDescending(arr, left, mid);
mergeSortDescending(arr, mid + 1,
right); merge(arr, left, mid, right);
}
}
private static void merge(int[] arr, int left, int mid, int
right) { int n1 mid - left + 1;
int n2 right - mid;
Easy 8
Level 9
+ i]; int i 0, j 0, k = left;
Easy 8
Level 9
while (i < n1 && j < n2)
if (leftArr[i] >= rightArr[j]) arr[k++] =
leftArr[i++]; else arr[k++] = rightArr[j++];
}
O(nlogn)O(n \
Merge Sort O(n)O(n) Large datasets, stable sorting
log n)
Easy 9
Level 0
Basic Array Operations
What is an array? Explain with examples.
Easy 91
Level
Sort an array in ascending order (without using sorting functions).
Sort an array in descending order (without using sorting functions).
Easy 92
Level