0% found this document useful (0 votes)
2 views94 pages

Array Tasks Easy Level

The document provides an overview of arrays in programming, detailing their definition, key features, and examples of declaration and initialization in Java. It explains how to access, update, and split arrays, along with practical examples and outputs. Additionally, it covers searching techniques such as linear search for finding elements within an array.

Uploaded by

er.arunscope
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views94 pages

Array Tasks Easy Level

The document provides an overview of arrays in programming, detailing their definition, key features, and examples of declaration and initialization in Java. It explains how to access, update, and split arrays, along with practical examples and outputs. Additionally, it covers searching techniques such as linear search for finding elements within an array.

Uploaded by

er.arunscope
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 94

Easy Level

🔹 Basic Array Operations 🚀


What is an array? Explain with examples.

📌 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.

🔹 Key Features of Arrays


✅ Index-Based Access * Elements can be accessed directly using an
index.
✅ Homogeneous (Same Data Type) * All elements must be of the
same type (e.g., int, float, char).
✅ Fixed Size * Once declared, the size cannot be changed.
✅ Stored in Contiguous Memory * Elements are stored next to each
other in memory.

🔹 Example: Declaring & Initializing an Array


Declare an Array

int[] arr; // Declaring an integer array

Allocate Memory (Fixed Size)

arr = new int[5]; // Allocating memory for 5 elements

Declare & Initialize Together

Easy 1
Level
int[] arr = 10, 20, 30, 40, 50; // Array with 5 elements

🔹 Accessing Elements in an Array


Each element in an array is accessed using an index, starting from 0.

public class ArrayExample {


public static void main(String[]
args) { int[] arr = 10, 20, 30,
40, 50;
// Access elements using index
System.out.println("First Element: " + arr[0]);
// 10 System.out.println("Third Element: " +
arr[2]); // 30 System.out.println("Last Element:
} " + arr[4]); // 50
}

✅ Output:

First Element: 10
Third Element: 30
Last Element: 50

🔹 Array Example: Storing Student Marks


Imagine you need to store marks of 5 students. Instead of using
multiple variables, we use an array with a meaningful name
students.
int[] students = 85, 90, 78, 92, 88; // Storing student marks

Now, we can loop through the array:

for (int i  0; i < students.length; i++) {


System.out.println("Student " + (i + 1) + " Marks: " + students[i]);

Easy 2
Level
}

✅ Output:

Student 1 Marks: 85
Student 2 Marks: 90
Student 3 Marks: 78
Student 4 Marks: 92
Student 5 Marks: 88

🔹 Real-World Example of an Array


Arrays are used everywhere in programming, including:
✔ Handling large data sets (e.g., student marks, employee salaries)
✔ Image processing (storing pixel values as arrays)
✔ Gaming (storing player scores, positions, or inventory items)
✔ Database management (storing structured data)

🔹 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.

How do you declare and initialize an array in


Java?

🔹 Declaring and Initializing an Array in Java


An array is a collection of elements of the same data type stored in
continuous memory locations. It allows easy access to elements using
an index.

✅ Declaration and Initialization

Easy 3
Level
Declaration Only

int[] arr; // Declaring an array

💡 No memory is allocated yet.

Declaration & Initialization Separately

int[] arr;
arr = new int[5]; // Allocating space for 5 elements

💡 Default values are assigned0 ( for int).

Declaration & Initialization Together

int[] arr = new int[5]; // Declares and initializes an array of size 5

Initializing with Values Directly

int[] arr = 10, 20, 30, 40, 50;

💡 Size is determined automatically.

Using new Keyword with Values

int[] arr = new int[]{5, 15, 25, 35, 45;

💡 Useful when passing an array to a method.

🔹 Different Data Types in Arrays


✅ Integer Array

int[] arr = 5, 10, 15, 20;

Easy 4
Level
✅ Double Array

double[] brr = 2.5, 3.8, 7.1;

✅ Character Array

char[] crr = {'X', 'Y', 'Z'};

✅ Boolean Array

boolean[] drr = {true, false, true};

✅ String Array with Jumbled Kannadiga Names

String[] players = {"Ehsan", "Chaitra", "Farhan", "Arjun",


"Bhavana", "Deepik a"};

🔹 Printing an Array
✅ Using a Loop

public class PrintArray {


public static void main(String[]
args) { int[] arr = 10, 20, 30,
40, 50;
System.out.print("Array elements:
"); for (int i  0; i < arr.length; i+
+) {
System.out.print(arr[i] + " ");
}
}

✅ Output:

Easy 5
Level
}
Array elements: 10 20 30 40 50
}

✅ Using Enhancedfor Loop

for (int num : arr) {


System.out.print(num + " ");
}

🔹 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
+)

✅ Thatʼs everything about declaring and initializing arrays in Java!

Write a program to print all elements of an


array.

Write a program to split an array into two


halves.

🔹 Approach 1: Basic Implementation Using


Loops
Splits the array into two halves

Handles both even and odd-length arrays

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];
}

// Copy elements into second


half for (int i = mid; i <
arr.length; i++) {
secondHalf[i - mid] = arr[i];
}

// Print the split arrays


System.out.print("First Half: ");
printArray(firstHalf);
System.out.print("Second Half: ");
printArray(secondHalf);
}

// Method to print an array


public static void printArray(int[]
arr) { for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}

public static void main(String[] args) {


// Sample Input
int[] arr = 10, 20, 30, 40, 50, 60, 70;

// Call method to split array


splitArray(arr);
}
}

✅ Output:

Easy 1
Level 0
First Half: 10 20 30 40
Second Half: 50 60 70

🔹 Approach 2: UsingSystem.arraycopy (Optimized


Uses built-in method for () )
efficiency Simplifies array

copying logic

public class
SplitArrayOptimized {

// Method to split the array into two halves using


System.arraycopy() public static void splitArray(int[] arr) {
int mid = (arr.length + 1) / 2; // Ensuring the first half gets extra
element if
odd

int[] firstHalf = new int[mid];


int[] secondHalf = new int[arr.length - mid];

// Copy first half using


System.arraycopy()
System.arraycopy(arr, 0, firstHalf, 0,
mid);

// Copy second half using System.arraycopy()


System.arraycopy(arr, mid, secondHalf, 0, arr.length - mid);

// Print the split arrays


System.out.print("First Half: ");
printArray(firstHalf);
System.out.print("Second Half: ");
printArray(secondHalf);
}

// Utility method to print an array


Easy 11
Level
public static void printArray(int[]
arr) {
for (int num : arr) {

Easy 12
Level
System.out.print(num +
" ");
}
} System.out.println();

public static void main(String[] args)


{
// Sample Input
int[] arr = 5, 15, 25, 35, 45, 55, 65,
// Call method to split
array
} splitArray(arr);
}

✅ Output:

First Half: 5 15 25 35
Second Half: 45 55 65 75

🔹 Sample Inputs & Expected Outputs


Input Array First Half Second Half
10, 20, 30, 40, 50, 60, 70 10, 20, 30, 40 50, 60, 70

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

How to update a specific element in an array?

🔹 Approach 1: Basic Index-Based Update


Access the element by

index. Assign a new

value.

Easy 13
Level
🔹 Implementation
public class UpdateArrayElement {

// Method to update an element at a specific index


public static void updateElement(int[] arr, int index, int
newValue) { if (index  0 || index >= arr.length) {
System.out.println("Invalid index! Please enter a valid
index."); return;
}

// Update the element


arr[index] = newValue;

// Print updated array


System.out.print("Updated Array: ");
printArray(arr);
}

// Utility method to print an array


public static void printArray(int[]
arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}

public static void main(String[] args) {


// Sample input array
int[] arr = 10, 20, 30, 40, 50;

// Print original array


System.out.print("Original Array: ");
printArray(arr);

// Update the element at index 2 (changing 30 to 99)

Easy 14
Level
updateElement(arr, 2,
} 99);
}

✅ Output:

Original Array: 10 20 30 40 50
Updated Array: 10 20 99 40 50

🔹 Approach 2: Update Multiple Elements in an


Array
What if we need to update multiple elements at once? We can use
a loop to update multiple indices.

🔹 Implementation
public class UpdateMultipleElements {

// Method to update multiple elements in an array


public static void updateMultiple(int[] arr, int[] indices, int[]
newValues) { if (indices.length ! newValues.length) {
System.out.println("Mismatch in indices and values
count!"); return;
}

for (int i  0; i < indices.length; i++)


{ int index = indices[i];

// Check if index is valid


if (index  0 && index < arr.length)
{ arr[index] = newValues[i];
} else {
System.out.println("Invalid index: " + index);
}
}

Easy 15
Level
// Print updated array
System.out.print("Updated Array: ");
printArray(arr);
}

// Utility method to print an array


public static void printArray(int[]
arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}

public static void main(String[] args) {


// Sample input array
int[] arr = 5, 10, 15, 20, 25;

// Indices to update and their new


values int[] indices = 1, 3;
int[] newValues = 99, 88;

// Print original array


System.out.print("Original Array: ");
printArray(arr);

// Update elements at given indices


updateMultiple(arr, indices, newValues);
}
}

✅ 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

1, 2, 3, 4, 5, 6 0, 5 100, 200 100, 2, 3, 4, 5, 200

🔍 Basic Searching & Traversing 🚀


Write a program to find a specific element in
an array (Linear Search).

🔹 Approach 1: Basic Linear Search


Traverse the array from the start.

If the element is found, return its index.

If the element is not present, return


1 .

🔹 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;

int index = findElement(arr,


target);
if (index ! -1) 
System.out.println("Element " + target + " found at index "
+ index);
} else {
System.out.println("Element " + target + " not found in the
array.");
}
}

✅ Output:

Element 37 found at index 2

🔹 Approach 2: Linear Search with Multiple


Occurrences
What if the target element appears multiple times? We return all indices
where the element is found.

🔹 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: ");

for (int i  0; i < arr.length; i+


+) {
if (arr[i] == target) {

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();
} }

public static void main(String[]


args) { int[] arr = 12, 34, 45,
34, 78, 34;

findAllOccurrences(arr,
} target);
}
✅ Output:

Element 34 found at index: 1 3 5

🔹 Sample Inputs & Expected Outputs


Input Array Target Output (Index/Indices)
Element
15, 28, 37, 44, 59 37 2

12, 34, 45, 34, 78, 34 34 1, 3, 5

1, 2, 3, 4, 5 6 "Element 6 not found in the


array."

Write a program to count occurrences of a


specific element in an array.

Easy 1
Level 8
🔹 Approach 1: Simple Iteration (Brute Force)
Iterate through the array.

Compare each element with the

target. If found, increment the

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;
}

public static void main(String[]


args) { int[] arr = 10, 20, 10, 30,
10, 40, 10;

int result = countOccurrences(arr, target);


System.out.println("Element " + target + " occurs " + result + "
} times.");
}
✅ Output:

Element 10 occurs 4 times.

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.

This approach is useful when elements have limited values.

🔹 Implementation
public class CountOccurrencesWithFrequencyArray {

// Method to count occurrences using frequency


array public static int countOccurrences(int[] arr, int
target) {
int maxValue  100; // Assuming numbers are within
0-100 int[] freq = new int[maxValue + 1;

for (int num : arr) {


freq[num]++; // Count each occurrence
}

return freq[target]; // Return frequency of target element


}

public static void main(String[]


args) { int[] arr = 5, 8, 5, 3, 5,
8, 8, 8;
int target  8;

int result = countOccurrences(arr, target);


System.out.println("Element " + target + " occurs " + result + "
times.");
}
}

✅ Output:

Element 8 occurs 4 times.

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.

The count =(last occurrence index - first occurrence .


index + 1)

🔹 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;
}
}

// Binary Search to find the last occurrence of


target public static int lastOccurrence(int[] arr,
int target) {
int low  0, high = arr.length - 1, last = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) {

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;
}

// Method to count occurrences using binary


search public static int countOccurrences(int[]
arr, int target) {
int first = firstOccurrence(arr, target);

if (first == -1) return 0; // Element not


found
} return last - first + 1;

public static void main(String[] args) {


int[] arr = 1, 2, 3, 3, 3, 4, 5, 6; // Sorted
array int target  3;

int result = countOccurrences(arr, target);


System.out.println("Element " + target + " occurs " + result + "
} times.");
}
✅ Output:

Element 3 occurs 3 times.

🔹 Sample Inputs & Expected Outputs

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)

2. Frequency Array: Useful for a small range of numbers. O(n)

3. Binary Search (Sorted Arrays): More efficient than linear search.


O(log n)

Find the first and last occurrence of a


number in an array.

🔹 Approach 1: Brute Force (Linear Search)


Traverse the array once to find the first
occurrence. Traverse again to find the last
occurrence.

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) {

// Traverse the array to find first and last


occurrences for (int i  0; i < arr.length; i++) {
if (arr[i] == target) {
Easy 23
Level
if (first == -1) 
first = i; // First occurrence
}
last = i; // Last occurrence (updates until the last
} match)
}

// 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);
}

public static void main(String[]


args) { int[] arr = 4, 2, 1, 2, 2,
3, 5, 2, 6;

findOccurrences(arr,
} target);
}
✅ Output:

First occurrence of 2 at index:


1 Last occurrence of 2 at
index: 7

🔹 Approach 2: Optimized for Sorted Arrays


(Binary Search)
Use Binary Search to find the first occurrence.

Easy 24
Level
Use Binary Search again to find the last

occurrence. Time Complexity: (Much faster

for sorted arrays).


O(logn)O(\log n)

🔹 Implementation
public class FirstLastOccurrenceBinarySearch {

// Method to find the first occurrence using binary


search public static int findFirstOccurrence(int[] arr,
int target) {
int low  0, high = arr.length - 1, first = -1;

while (low <= high) {


int mid = low + (high - low) /
2; if (arr[mid] == target) {
first = mid; // Possible first
occurrence high = mid - 1; // Search
in the left half
} else if (arr[mid] <
target) { low = mid +
1;
} else {
high = mid - 1;
}
}
return first;
}

// Method to find the last occurrence using


binary search public static int
findLastOccurrence(int[] arr, int target) {
int low  0, high = arr.length - 1, last = -1;

while (low <= high) {


int mid = low + (high - low) /
2; if (arr[mid] == target) {
Easy 25
Level
last = mid; // Possible last occurrence
low = mid + 1; // Search in the right half

Easy 26
Level
} else if (arr[mid] <
target) { low = mid +
1;
} else {
high = mid - 1;
}
}
} return last;

public static void main(String[] args) {


int[] arr = 1, 2, 2, 2, 3, 4, 5, 6; // Sorted
array int target  2;

int first = findFirstOccurrence(arr,


target);
int last = findLastOccurrence(arr,
if (first == -1) 
System.out.println("Element " + target + " not found.");
} else {
System.out.println("First occurrence of " + target + " at
t); index: " + firs
System.out.println("Last occurrence of " + target + " at index:
} " + last);
}
}
✅ Output:

First occurrence of 2 at index:


1 Last occurrence of 2 at
index: 3

🔹 Approach 3: Using a Single Pass (Optimized


Linear Search)
Instead of two loops, we traverse the array once.

Easy 27
Level
This reduces redundant traversal, improving efficiency.

🔹 Implementation
public class FirstLastOccurrenceSinglePass {

// Optimized single-pass linear search method


public static void findOccurrences(int[] arr, int
target) { int first = -1, last = -1;

for (int i  0; i < arr.length; i+


+) { if (arr[i] == target) {
if (first == -1) first = i; // First occurrence
last = i; // Last occurrence (updates till the end)
}
}

if (first == -1) 
System.out.println("Element " + target + " not found.");
} else {
System.out.println("First occurrence of " + target + " at index: "
t); + firs

System.out.println("Last occurrence of " + target + " at index: "


+ last);
}
}

public static void main(String[]


args) { int[] arr = 4, 5, 6, 5, 7,
5, 8;
int target  5;

findOccurrences(arr, target);
}
}

✅ Output:

Easy 28
Level
First occurrence of 5 at index:
1 Last occurrence of 5 at
index: 5

🔹 Sample Inputs & Expected Outputs


Input Array Target First Last
Occurrence Occurrence
4, 2, 1, 2, 2, 3, 5, 2, 2 1 7
6
1, 2, 2, 2, 3, 4, 5, 6 2 1 3

5, 8, 5, 3, 5, 8, 8, 8 8 5 7

2, 4, 6, 8, 10 7 -1 (Not found) -1 (Not found)

📌 Key Takeaways
1. Brute Force (Linear Search) O(n)O(n): Simple but slow for large
arrays.

2. Binary Search (For Sorted Arrays) O(logn)O(\log n): Efficient when


the array is sorted.

3. Single Pass Linear Search O(n)O(n): Optimized version of linear


search (Best for unsorted arrays).

Check if an array contains a given number.

🔹 Approach 1: Brute Force (Linear Search)


Traverse the array element by element.

If any element matches the target,

return true. If no match is found, return

false.

Time Complexity: (Linear time).


O(n)O(n)

🔹 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;

// Checking if the array contains the


target 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:

The array contains the number 30

🔹 Approach 2: Optimized for Sorted Arrays


(Binary Search)
Prerequisite: The array must be sorted.

Use Binary Search to find the element efficiently.

Easy 29
Level
Time Complexity: (Faster for large arrays).
O(logn)O(\log n)

🔹 Implementation
public class ArrayContainsBinarySearch {

// Method to check if a number exists using binary


search public static boolean containsNumber(int[]
arr, int target) {
int low  0, high = arr.length - 1;

while (low <= high) {


int mid = low + (high - low) / 2;

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
}

public static void main(String[] args) {


int[] arr = 5, 10, 15, 20, 25, 30, 35; // Sorted
array int target  15;

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:

The array contains the number 15

🔹 Approach 3: Using a Hashing Technique


Store all array elements in a boolean array (hash

table). Quick lookup using indexing.

Time Complexity: (Preprocessing) + (Lookup).


O(n)O(n)
O(1)O(1)

🔹 Implementation
public class ArrayContainsHashing {

// Method to check if an array contains the target number using


hashing public static boolean containsNumber(int[] arr, int
target) {
boolean[] hash = new boolean[100001; // Assuming numbers
are in rang e 0-100000

for (int num : arr) {


hash[num] = true; // Mark presence
}

return hash[target]; // Check presence


}

public static void main(String[]


args) { int[] arr = 12, 45, 78,
89, 23, 56;
int target  23;

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:

The array contains the number 23

🔹 Sample Inputs & Expected Outputs


Input Array Target Output
10, 20, 30, 40, 50 30 ✅ Yes
1, 2, 3, 4, 5 7 ❌ No
100, 200, 300, 400 300 ✅ Yes
5, 10, 15, 20, 25 50 ❌ No

📌 Key Takeaways
1. Brute Force (Linear Search) O(n)O(n): Simple but slow for large
arrays.

2. Binary Search (For Sorted Arrays) O(logn)O(\log n): Efficient for


sorted data.

3. Hashing (Quick Lookup) O(n)O(n): Preprocessing takes time, but


lookup is instant.

🔟 Write a program to find the sum of all


elements in an array.

🔹 Approach 1: Using a Simple Loop (Brute


Force)
Easy 32
Level
Initialize sum  0 .

Iterate over each element and add it


sumto .

Time Complexity: (Linear Time).


O(n)O(n)

🔹 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;
}

public static void main(String[]


args) {
int[] arr = 10, 20, 30, 40, 50;
// Calculating sum
int totalSum = findSum(arr);
System.out.println("Sum of all elements: " +
} totalSum);
}
✅ Output:

Sum of all elements: 150

🔹 Approach 2: Using Recursion


Recursively sum the array elements.

Easy 33
Level
Base Case: If the array is empty, return
0 .

Recursive Case: Sum of the first element + sum of the remaining


elements.

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);
}

// Helper function for recursion


private static int findSumHelper(int[] arr, int
index) { if (index == arr.length) {
return 0;
}
return arr[index] + findSumHelper(arr, index
+ 1);
}

public static void main(String[]


args) {
int[] arr = 5, 15, 25, 35;
// Calculating sum using
recursion int totalSum =
findSum(arr);
}
}
✅ Output:

Sum of all elements: 80

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);
}

private static int findSumHelper(int[] arr, int left, int


right) { if (left > right) {
return 0;
}
if (left == right)
{ return arr[left];
}
int mid = left + (right - left) / 2;
return findSumHelper(arr, left, mid) + findSumHelper(arr, mid +
1, right);
}

public static void main(String[]


args) {
int[] arr = 3, 6, 9, 12, 15;
// Calculating sum using divide &
conquer int totalSum = findSum(arr);
System.out.println("Sum of all elements: " +
} totalSum);
}

Easy 35
Level
✅ Output:

Sum of all elements: 45

🔹 Sample Inputs & Expected Outputs


Input Array Output (Sum)
1, 2, 3, 4, 5 15

10, 20, 30 60

100, 200, 300 600

5, 10, 15, 20, 25 75

📌 Key Takeaways
1. Iterative Approach (Brute Force) O(n)O(n): Simple and effective.

2. Recursive Approach O(n)O(n): Uses function calls, but avoids


unnecessary arguments.

3. Divide & Conquer O(n)O(n): Breaks the problem into smaller


subproblems.

🔄 Basic Array Transformations ✨


Reverse an array without using extra space.

🔹 Approach 1: Using Two-Pointer Technique


(Optimal)
Swap the first and last elements, then the second and second-last,
and so on.

Time Complexity: (Iterates through half the array).


O(n)O(n)

Space Complexity: (No extra space used).


O(1)O(1)

Easy 36
Level
🔹 Implementation
public class ReverseArray {

// Method to reverse an array using the Two-Pointer


technique public static void reverseArray(int[] arr) {
int left  0, right = arr.length - 1;

while (left < right) {


// Swap elements at left and right
positions int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;

left+
+;
right--
;
}
}

// Method to print the array


public static void printArray(int[]
arr) { for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}

public static void main(String[]


args) { int[] arr = 1, 2, 3, 4, 5;

System.out.println("Original Array:");
printArray(arr);

// Reverse the array


reverseArray(arr);

Easy 37
Level
System.out.println("Reversed
Array:");
} printArray(arr);
}

✅ Output:

Original
Array: 1 2 3
45
Reversed
Array: 5 4 3 2

🔹 Approach 2: Using Recursion


Swap first and last elements, then recursively reverse the remaining
elements.

Time Complexity:
O(n)O(n)

Space Complexity: (Recursive call stack).


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);

public static void printArray(int[]


arr) { for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}

public static void main(String[]


args) {
int[] arr = 10, 20, 30, 40, 50;
System.out.println("Original
Array:");
printArray(arr);
// Reverse using recursion
reverseArray(arr, 0, arr.length
- 1);
System.out.println("Reversed
Array:");
} printArray(arr);
}
✅ Output:

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) {

while (left < right) {


arr[left] = arr[left] ^
arr[right]; arr[right] =
arr[left] ^ arr[right]; arr[left]
= arr[left] ^ arr[right];
left+
+;
} right--;
}

public static void printArray(int[]


arr) { for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}

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

🔹 Sample Inputs & Expected Outputs


Input Array Output
(Reversed)
1, 2, 3, 4, 5 5, 4, 3, 2, 1

10, 20, 30 30, 20, 10

5, 15, 25, 35 35, 25, 15, 5

📌 Key Takeaways
1. Two-Pointer Swap O(n)O(n): Best approach, simple and efficient.

2. Recursion O(n)O(n): Uses stack memory, not as optimal.

Easy 41
Level
3. XOR Swap O(n)O(n): Avoids using a temp variable but is tricky.

🔹 Approach 1: Using a New Array (Simplest


Method)
Create a new array of the same size.

Copy elements from the original array in reverse order.

Time Complexity: (Iterates through the array once).


O(n)O(n)

Space Complexity: (Uses extra array).


O(n)O(n)

🔹 Implementation
public class
ReverseArrayExtraSpace {
// Method to reverse an array using extra
space public static int[] reverseArray(int[]
arr) {
int n = arr.length;

for (int i  0; i < n; i++) {


brr[i] = arr[n - i - 1; // Copy in reverse
order
}
} return brr;

// Method to print the array


public static void printArray(int[]
arr) { for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}

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

🔹 Approach 2: Using a Stack (LIFO - Last In,


First Out)
Push all elements into a stack.

Pop elements one by one into a new array.

Time Complexity:
O(n)O(n)

Space Complexity: (Uses stack memory).


O(n)O(n)

🔹 Implementation

Easy 43
Level
import java.util.Stack;

public class ReverseArrayStack {

// Method to reverse an array using a stack


public static int[] reverseArray(int[] arr) {
Stack<Integer> stack = new
Stack<>(); int n = arr.length;
int[] brr = new int[n];

// Push all elements to


stack for (int num : arr) {
stack.push(num);
}

// Pop elements back to new


array for (int i  0; i < n; i++)
{
brr[i] = stack.pop();
}

return brr;
}

public static void printArray(int[]


arr) { for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}

public static void main(String[]


args) { int[] arr = 10, 20, 30,
40, 50;

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

🔹 Approach 3: Using Recursion with Extra


Space
Store elements in a new array while calling the function recursively.

Time Complexity:
O(n)O(n)

Space Complexity: (Recursive call stack).


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);

public static void printArray(int[]


arr) { for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}

public static void main(String[]


args) {
int[] arr = 5, 15, 25, 35, 45;
System.out.println("Original
Array:");
printArray(arr);
int[] reversedArr = new
int[arr.length];
// Reverse using recursion
reverseArray(arr,
reversedArr, 0);
System.out.println("Reversed
Array:");
} printArray(reversedArr);
}
✅ Output:

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

10, 20, 30 30, 20, 10

5, 15, 25, 35 35, 25, 15, 5

📌 Key Takeaways
1. Using a New Array O(n)O(n): Easiest method, straightforward.

2. Using a Stack O(n)O(n): Utilizes LIFO property but requires extra


space.

3. Using Recursion O(n)O(n): Not optimal due to extra call stack space.

Find the maximum and minimum value in an


array.

🔹 Approach 1: Brute Force (Simple Traversal)


Traverse the array once.

Compare each element to maintain max and min values.

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];
}
}

System.out.println("Minimum Value: " +


min);
} System.out.println("Maximum Value: " +

public static void main(String[]


args) {
int[] arr = 12, 3, 8, 22, 15;
System.out.println("Given
Array:"); for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();

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.

Min: First element

Max: Last element

Time Complexity: (Sorting overhead).


O(nlogn)O(n \log n)

Space Complexity: (In-place sorting).


O(1)O(1)

🔹 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;
}
}

// Min is first element, Max is last element


System.out.println("Minimum Value: " + arr[0]);
System.out.println("Maximum Value: " +
} arr[arr.length - 1);

public static void main(String[]


args) {

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

🔹 Approach 3: Divide and Conquer (Optimized)


Divide the array into two halves recursively.

Compare min/max of both halves.

Time Complexity:
O(n)O(n)

Space Complexity: (Recursive call stack).


O(logn)O(\log 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;
}

if (right == left + 1)  // Two elements


case if (arr[left] < arr[right]) {
result[0] = arr[left]; // min
result[1] = arr[right]; // max
} else {
result[0] = arr[right]; // min
result[1] = arr[left]; // max
}
return;
}

int mid = (left + right) / 2;

int[] leftResult = new int[2];


int[] rightResult = new
int[2];

findMinMax(arr, left, mid, leftResult);


findMinMax(arr, mid + 1, right,
rightResult);

// Merge results
result[0]  Math.min(leftResult[0],
rightResult[0]); result[1] 
Math.max(leftResult[1], rightResult[1]);
}

public static void main(String[]


args) { int[] arr = 45, 7, 12, 90,
23, 8;

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

🔹 Sample Inputs & Expected Outputs


Input Array Minimum Maximum
Value Value
12, 3, 8, 22, 15 3 22

5, 25, 15, 7, 30 5 30

45, 7, 12, 90, 23, 8 7 90

📌 Key Takeaways
1. Brute Force O(n)O(n): Best for simple cases.

2. Sorting O(nlogn)O(n \log n): Avoid if unnecessary.

3. Divide & Conquer O(n)O(n): Optimized, but recursive.

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.
)

🔹 Approach 1: Using Simple Iteration (Brute


Force)
Iterate through the original array
arr ( ).

Copy each element into the new array


brr ( ).

Time Complexity:
O(n)O(n)

Space Complexity: (New array storage).


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];

for (int i  0; i < n; i++) {


brr[i] = arr[i]; // Copying
elements
}
} return brr;

public static void main(String[]


args) {
int[] arr = 10, 20, 30, 40, 50;
System.out.println("Original
Array:");
Easy 54
Level
for (int num : arr) {
System.out.print(num +
" ");
}
System.out.println();
int[] brr =
copyArray(arr);
System.out.println("Copied
Array:"); for (int num : brr) {
System.out.print(num + " ");
}
}
}

✅ Output:

Original Array:
10 20 30 40
50
Copied Array:
10 20 30 40

🔹 Approach 2: Copying Elements in Reverse


Order
Instead of copying in the same order, reverse elements
brr into .

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];

for (int i  0; i < n; i++) {


brr[i] = arr[n - i - 1; // Copying in reverse
order
}
} return brr;

public static void main(String[]


args) {
int[] arr = 5, 10, 15, 20, 25;
System.out.println("Original
Array:"); for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();

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)

Space Complexity: (in worst case if all numbers are even).


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

🔹 Sample Inputs & Expected Outputs


Copied Array (Same Copied Array Copied
Input Array
Order) (Reverse Order) Even
Numbers
10, 20, 30, 40,
10, 20, 30, 40, 50 50, 40, 30, 20, 10 10, 20, 30, 40, 50
50

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.

3. Filtered Copy O(n)O(n): Copies only even numbers.

Swap the first and last elements of an array.

🔹 Approach 1: Using a Temporary Variable


(Basic Swapping)
Steps:

1. Store the first element in a temporary variable.

2. Assign the last element to the first position.

3. Assign the stored value to the last position.

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

int temp = arr[0];


arr[0] = arr[arr.length -
1;

Easy 58
Level
arr[arr.length - 1  temp;
}

public static void main(String[]


args) {
int[] arr = 10, 20, 30, 40, 50;
System.out.println("Before Swap:");
for (int num : arr) System.out.print(num +
" "); System.out.println();

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

🔹 Approach 2: Swapping Without a Temporary


Variable (Using Multiplication & Division)
This method uses multiplication and division instead of a temporary
variable.

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;
}

public static void main(String[]


args) {
int[] arr = 2, 4, 6, 8, 10;
System.out.println("Before Swap:");
for (int num : arr) System.out.print(num +
" "); System.out.println();

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)

Works in all cases except integer overflow.

🔹 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;
}

public static void main(String[]


args) {
int[] arr = 5, 10, 15, 20, 25;
System.out.println("Before Swap:");
for (int num : arr) System.out.print(num +
" "); System.out.println();

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

🔹 Approach 4: Swapping Using XOR (Bitwise


Operator)
Uses XOR swap algorithm, avoiding extra space and arithmetic
operations.

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;
}

arr[0] = arr[0] ^ arr[arr.length


- 1;

Easy 62
Level
arr[arr.length - 1  arr[0] ^ arr[arr.length -
1;
} arr[0] = arr[0] ^ arr[arr.length - 1;

public static void main(String[]


args) {
int[] arr = 3, 6, 9, 12, 15;
System.out.println("Before Swap:");
for (int num : arr) System.out.print(num +
" "); System.out.println();

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

🔹 Sample Inputs & Expected Outputs


Input Array After Swap
10, 20, 30, 40, 50 50, 20, 30, 40, 10

2, 4, 6, 8, 10 10, 4, 6, 8, 2

5, 10, 15, 20, 25 25, 10, 15, 20, 5

3, 6, 9, 12, 15 15, 6, 9, 12, 3

Easy 63
Level
📌 Key Takeaways
1. Basic Swap (O(1)): Uses a temporary variable.

2. Multiplication & Division Swap (O(1)): Risky if zeros exist.

3. Addition & Subtraction Swap (O(1)): Avoids extra space, risks


overflow.

4. XOR Swap (O(1)): Avoids extra space, works well in all cases.

Rotate an array to the left by one position.

🔹 Approach 1: Using a Temporary Variable


(Brute Force)
Steps:

1. Store the first element in a temporary variable.

2. Shift all elements left by one position.

3. Move the stored element to the last index.

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
}

int temp = arr[0]; // Store first


element

Easy 64
Level
for (int i  0; i < arr.length - 1; i++) {
arr[i] = arr[i + 1; // Shift
elements left
}
}

public static void main(String[]


args) {
int[] arr = 1, 2, 3, 4, 5;
System.out.println("Before Rotation:");
for (int num : arr) System.out.print(num +
" "); System.out.println();

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

🔹 Approach 2: Using a Swap-Based Approach


Instead of using a temporary array, we swap elements in-place.

Time Complexity:
O(n)O(n)

Space Complexity:

Easy 65
Level
O(1)O(1)

🔹 Implementation
public class LeftRotateSwap {

// Swap-based left rotation


public static void leftRotateByOneSwap(int[]
arr) { if (arr.length  2) 
return;
}

for (int i  0; i < arr.length - 1; i+


+) { int temp = arr[i];
arr[i] = arr[i + 1;
arr[i + 1  temp;
}
}

public static void main(String[]


args) { int[] arr = 10, 20, 30,
40, 50;

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

🔹 Approach 3: Using Reversal Algorithm


(Efficient)
This approach is based on reversing parts of the array.

Steps:

1. Reverse the entire array.

2. Reverse the first n-1 elements.

3. Reverse the last element separately.

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;
}

reverse(arr, 0, arr.length - 1); // Reverse the entire


array reverse(arr, 0, arr.length - 2); // Reverse
first n-1 elements reverse(arr, arr.length - 1, arr.length -
1); // Reverse last element
}

public static void main(String[]


args) { int[] arr = 5, 10, 15, 20,
25;

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

🔹 Sample Inputs & Expected Outputs

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

5, 10, 15, 20, 25 10, 15, 20, 25, 5

100, 200, 300 200, 300, 100

📌 Key Takeaways
1. Brute Force Approach (O(n)): Uses a temporary variable for storing
the first element.

2. Swap-Based Approach (O(n)): Swaps elements in-place.

3. Reversal Algorithm (O(n)): Efficient and requires no extra space.

🔢✨ Basic Mathematical Operations on


Arrays ➕➖✖➗
Write a program to find the average of an
array.

🔹 Approach 1: Using Simple Iteration (Brute


Force)
Steps:

1. Traverse the array and compute the sum.

2. Divide the sum by the number of elements to get the average.

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
}

public static void main(String[]


args) {
int[] arr = 10, 20, 30, 40, 50;
System.out.println("Array Average: " +
} findAverage(arr));
}
✅ Output:

Array Average: 30.0

🔹 Approach 2: Using Recursion


Instead of using a loop, we calculate the sum recursively and then
compute the average.

Time Complexity:
O(n)O(n)

Space Complexity: (due to recursive


stack) O(n)O(n)

Easy 70
Level
🔹 Implementation
public class ArrayAverageRecursive {

// Recursive function to compute sum


public static int computeSum(int[] arr, int
index) { if (index == arr.length) return 0;
return arr[index] + computeSum(arr, index + 1);
}

// Method to find average using recursion


public static double findAverageRecursive(int[]
arr) { if (arr.length  0) return 0;
int sum = computeSum(arr,
0); return (double) sum /
arr.length;
}

public static void main(String[]


args) { int[] arr = 5, 15, 25, 35,
45;

System.out.println("Array Average: " + findAverageRecursive(arr));


}
}

✅ Output:

Array Average: 25.0

🔹 Approach 3: Using a Mathematical Formula


(Avoiding Overflow)
Instead of maintaining a sum, we calculate the incremental
average to prevent overflow.

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;

public static void main(String[]


args) {
int[] arr = 7, 14, 21, 28, 35;
System.out.println("Array Average: " +
} findAverageOptimized(arr));
}
✅ Output:

Array Average: 21.0

🔹 Sample Inputs & Expected Outputs

Easy 72
Level
Input Array Average
Output
10, 20, 30, 40, 50 30.0

5, 15, 25, 35, 45 25.0

7, 14, 21, 28, 35 21.0

1, 3, 5, 7, 9 5.0

📌 Key Takeaways
1. Brute Force Approach (O(n)) * Simple and efficient for most cases.

2. Recursive Approach (O(n)) * Alternative but uses extra space.

3. Incremental Formula (O(n)) * Avoids overflow in case of large


numbers.

Find the second largest and second smallest


element in an array.

🔹 Approach 1: Brute Force (Sorting)


Steps:

1. Sort the array in ascending order.

2. Pick the second element for the second smallest.

3. Pick the second-last element for the second largest.

Time Complexity: (due to


sorting) O(nlogn)O(n \log n)

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;
}

Arrays.sort(arr); // Sorting the

array int secondSmallest =

arr[1];
int secondLargest = arr[arr.length - 2;

System.out.println("Second Smallest: " + secondSmallest);


System.out.println("Second Largest: " + secondLargest);
}

public static void main(String[]


args) { int[] arr = 12, 5, 8, 19,
7, 25;

findSecondLargestSmallest(arr);
}
}

✅ Output:

Second Smallest: 7
Second Largest: 19

🔹 Approach 2: Single Pass (Without Sorting)


Steps:

1. Use two variables to track the smallest & second smallest.

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 {

// Method to find second smallest and second largest without


sorting public static void findSecondLargestSmallest(int[] arr) {
if (arr.length  2) 
System.out.println("Array must have at least two
elements."); return;
}

int smallest  Integer.MAX_VALUE, secondSmallest  Integer.MAX_VALU


E;
int largest  Integer.MIN_VALUE, secondLargest  Integer.MIN_VALUE;

for (int num : arr) {


// Finding smallest and second
smallest if (num < smallest) {
secondSmallest = smallest;
smallest = num;
} else if (num < secondSmallest && num !  smallest)
{ secondSmallest = num;
}

// Finding largest and second


largest if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num ! largest)
{ secondLargest = num;

Easy 76
Level
}
}

if (secondSmallest  Integer.MAX_VALUE || secondLargest 


Integer.M IN_VALUE) 
System.out.println("No second largest or second smallest
element fou
nd.");
} else {
System.out.println("Second Smallest: " + secondSmallest);
System.out.println("Second Largest: " + secondLargest);
}
}

public static void main(String[]


args) {
int[] arr = 18, 12, 5, 8, 19, 7, 25;
findSecondLargestSmallest(a
} rr);
}
✅ Output:

Second Smallest: 7
Second Largest: 19

🔹 Sample Inputs & Expected Outputs


Input Array Second Second
Smallest Largest
12, 5, 8, 19, 7, 25 7 19

1, 2, 3, 4, 5 2 4

99, 45, 12, 67, 34 34 67

10, 10, 10, 10 Not Found Not Found

Easy 77
Level
📌 Key Takeaways
1. Sorting Approach (O(n log n)) * Easy to implement but inefficient
for large arrays.

2. Single Pass (O(n)) * Efficient, avoids sorting.

Write a program to remove duplicate elements


from an array.
🔹 Approach 1: Using Nested Loops (Brute Force)
Time
Complexity:
O(n2)O(n^2)

Space Complexity: (No extra space


used) O(1)O(1)

Method: Check each element and shift non-duplicates to the left.

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

array int newSize = n; // Size of array after removing duplicates

for (int i  0; i < newSize; i++) {


for (int j = i + 1; j < newSize; j++) {
if (arr[i] == arr[j]) { // If duplicate found
// Shift elements to the left
for (int k = j; k < newSize - 1; k++)
{ arr[k] = arr[k + 1;
}
newSize--; // Reduce array size
j--; // Check new element at same position
}

Easy 77
Level
}
}
return newSize; // Return new array
} size

public static void main(String[] args)


{ int[] arr = 5, 3, 8, 3, 2, 8, 1;
int newSize =
removeDuplicatesBruteForce(arr);
System.out.print("Array after removing
duplicates: "); for (int i  0; i < newSize; i++) {
System.out.print(arr[i] + " ");
}
}
}

🔹 Approach 2: Using Sorting (Better than Nested Loops)


Time Complexity: (Due to
sorting) O(nlogn)O(n \log n)
Space
Complexity:
O(1)O(1)
import
java.util.Arrays;
class RemoveDuplicates {
// Method to remove duplicates using sorting
public static int
removeDuplicatesUsingSorting(int[] arr) { int n
= arr.length;

Arrays.sort(arr); // Sort array first


int j  0; // Index to store unique
elements

Easy 78
Level
for (int i  0; i < n - 1; i+
+) { if (arr[i] ! arr[i +
1) 
arr[j++] = arr[i]; // Store unique
elements
}
}

return j; // Return new


} size

public static void main(String[] args)


{ int[] arr = 4, 2, 7, 2, 4, 8, 9, 7;
int newSize =
removeDuplicatesUsingSorting(arr);
System.out.print("Array after removing
duplicates: "); for (int i  0; i < newSize; i++) {
System.out.print(arr[i] + " ");
}
}
}

🔹 Approach 3: Optimized Two-Pointer Method (For Sorted


Arrays)
Time
Complexity:
O(n)O(n)
Space
Complexity:
O(1)O(1)
class RemoveDuplicates {
public static int removeDuplicatesOptimized(int[]
arr) { int n = arr.length;
if (n  0 || n  1) return n;

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
}

public static void main(String[] args)


{ int[] arr = 1, 1, 2, 2, 3, 4, 4, 5;
int newSize =
removeDuplicatesOptimized(arr);
System.out.print("Array after removing
duplicates: "); for (int i  0; i < newSize; i++) {
System.out.print(arr[i] + " ");
}
}
}

✅ 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

Two-Pointer (Optimized for When array is


O(n)O(n) O(1)O(1)
Sorted Array) already sorted

Easy 8
Level 0
Sort an array in ascending order (without
using sorting functions).

🔹 Approach 1: Bubble Sort (Simple but


Inefficient)
Time
Complexity:
O(n2)O(n^2)

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;
}
}
}
}

public static void main(String[]


args) { int[] arr = 5, 3, 8, 1, 2;
bubbleSort(arr);
System.out.print("Sorted array:
"); for (int num : arr) {
System.out.print(num + " ");
}
Easy 81
Level
}
}

🔹 Approach 2: Selection Sort


Time
Complexity:
O(n2)O(n^2)

Space
Complexity:
O(1)O(1)

Method: Selects the smallest element and places it in the correct


position.
class SelectionSort {
public static void selectionSort(int[]
arr) { int n = arr.length;
for (int i  0; i < n - 1; i+
+) { int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex])
{ minIndex = j;
}
}
// Swap the found minimum element with the first
element int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}

public static void main(String[]


args) { int[] arr = 7, 4, 10, 8, 3,
1; selectionSort(arr);
System.out.print("Sorted array:
");
for (int num : arr) {
Easy 82
Level
System.out.print(num +
} " ");
}
}

🔹 Approach 3: Insertion Sort (Efficient for


Small Data Sets)
Time
Complexity:
O(n2)O(n^2)

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;
}
}

public static void main(String[]


args) { int[] arr = 9, 7, 5, 3, 1;
insertionSort(arr);
System.out.print("Sorted array:
");
for (int num : arr) {
Easy 83
Level
System.out.print(num +
} " ");
}
}

🔹 Approach 4: Merge Sort (Optimized for Large


Data Sets)
Time
Complexity:
O(nlogn)O(n \log
n)

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;

int[] leftArr = new


int[n1];
int[] rightArr = new
for (int i  0; i < n1; i++) leftArr[i] = arr[left + i];
Easy
Level
for (int i  0; i < n2; i++) rightArr[i] = arr[mid + 84

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++];
}

while (i < n1) arr[k++] = leftArr[i+


+];
} while (j < n2) arr[k++] =

public static void main(String[]


args) { int[] arr = 12, 11, 13, 5,
6, 7;
mergeSort(arr, 0, arr.length -
1);
System.out.print("Sorted array:
"); for (int num : arr) {
System.out.print(num + " ");
}
}

✅ Summary of Sorting Techniques:


Sorting Space
Time Complexity Best Use Case
Algorithm Complexity

Small datasets, simple


Bubble Sort O(n2)O(n^2) O(1)O(1)
implementation

When memory optimization is


Selection Sort O(n2)O(n^2) O(1)O(1)
needed

When the array is partially


Insertion Sort O(n2)O(n^2) O(1)O(1)
sorted

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).

🔹 Approach 1: Bubble Sort (Simple but


Inefficient)
Time
Complexity:
O(n2)O(n^2)

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;
}
}
}
}

public static void main(String[]


args) { int[] arr = 5, 3, 8, 1, 2;
bubbleSortDescending(arr);
System.out.print("Sorted array:
"); for (int num : arr) {
System.out.print(num + " ");
}

Easy 86
Level
}
}

🔹 Approach 2: Selection Sort


Time
Complexity:
O(n2)O(n^2)

Space
Complexity:
O(1)O(1)

Method: Selects the largest element and places it in the correct


position.
class SelectionSortDescending {
public static void selectionSortDescending(int[]
arr) { int n = arr.length;
for (int i  0; i < n - 1; i+
+) { int maxIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] > arr[maxIndex]) { // Change < to > for descending
order maxIndex = j;
}
}
int temp =
arr[maxIndex];
arr[maxIndex] = arr[i];
arr[i] = temp;
}
}

public static void main(String[]


args) { int[] arr = 7, 4, 10, 8, 3,
1; selectionSortDescending(arr);
System.out.print("Sorted array:
"); for (int num : arr) {
System.out.print(num + " ");

Easy 87
Level
}
}
}

🔹 Approach 3: Insertion Sort


Time
Complexity:
O(n2)O(n^2)

Space
Complexity:
O(1)O(1)

Method: Builds the sorted array one element at a time.

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;
}
}

public static void main(String[]


args) { int[] arr = 9, 7, 5, 3, 1;
insertionSortDescending(arr);
System.out.print("Sorted array:
"); for (int num : arr) {
System.out.print(num + " ");
}

Easy 8
Level 8
}
}

🔹 Approach 4: Merge Sort (Efficient for Large


Data Sets)
Time
Complexity:
O(nlogn)O(n \log
n)

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;

int[] leftArr = new int[n1];


int[] rightArr = new
int[n2];

for (int i  0; i < n1; i++) leftArr[i] = arr[left + i];


for (int i  0; i < n2; i++) rightArr[i] = arr[mid + 1

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++];
}

while (i < n1) arr[k++] = leftArr[i+


+];
} while (j < n2) arr[k++] =

public static void main(String[] args)


{ int[] arr = 12, 11, 13, 5, 6, 7;
mergeSortDescending(arr, 0,
arr.length - 1);
System.out.print("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
} }

✅ Summary of Sorting Techniques:


Sorting Space
Time Complexity Best Use Case
Algorithm Complexity

Small datasets, simple


Bubble Sort O(n2)O(n^2) O(1)O(1)
implementation

When memory optimization is


Selection Sort O(n2)O(n^2) O(1)O(1)
needed

When the array is partially


Insertion Sort O(n2)O(n^2) O(1)O(1)
sorted

O(nlogn)O(n \
Merge Sort O(n)O(n) Large datasets, stable sorting
log n)

Write a program to merge two arrays into a third array.

Easy 9
Level 0
Basic Array Operations
What is an array? Explain with examples.

How do you declare and initialize an array in Java?


Write a program to print all elements of an array.
Write a program to split an array into two halves.
How to update a specific element in an array?

Basic Searching & Traversing


Write a program to find a specific element in an array (Linear
Search).
Write a program to count occurrences of a specific element in an
array.
Find the first and last occurrence of a number in an array.
Check if an array contains a given number.

🔟 Write a program to find the sum of all elements in an array.

Basic Array Transformations


Reverse an array without using extra space.
Find the maximum and minimum value in an array.
Write a program to copy elements from one array to another.

Swap the first and last elements of an array.

Rotate an array to the left by one position.

Basic Mathematical Operations on Arrays


Write a program to find the average of an array.
Find the second largest and second smallest element in an array.
Write a program to remove duplicate elements from an array.

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

You might also like