Arrays: 10 Practice Problems and Solutions
This is the solution for the practice question set on the concept of arrays in programming languages, their properties, as well as different operations based on arrays.
You can find the corresponding list of questions here. Try solving the questions yourself before you go through the solutions.
Problem: Write a function to reverse an array in place.
Example: Input: `[1, 2, 3, 4, 5]` → Output: `[5, 4, 3, 2, 1]`
CODE :
import java.io.*;
class Main {
public static void main(String[] args)
{
//declaring all variables
int i,left,right,temp;
int[] arr = {1,2,3,4,5};
//printing original array
System.out.println("Original Array : ");
for(int num : arr)
{
System.out.print(num+" ");
}
//reversing array
left = 0;
right = arr.length-1;
while(left<right)
{
//swapping values at indices
temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
//moving pointers
left++;
right--;
}
//printing reversed array
System.out.println("\nReversed Array : ");
for(int num : arr)
{
System.out.print(num+" ");
}
}
}
Problem: Write a function to rotate an array to the right by `k` positions.
Example: Input: `[1, 2, 3, 4, 5]`, `k = 2` → Output: `[4, 5, 1, 2, 3]`
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//declaring all variables
int[] arr={1,2,3,4,5};
int i,k,size=arr.length;
System.out.println("Enter value of k : ");
k = sc.nextInt();
//for cases where k > size
k = k % size;
//printing original array
System.out.println("Original Array : ");
for(int num : arr)
{
System.out.print(num+" ");
}
//rotating the array
int[] temp = new int[size];
for(i=0;i<size;i++)
{
temp[(i+k)%size]=arr[i];
}
//printing rotated array
System.out.println("\nRotated Array : ");
for(int num : temp)
{
System.out.print(num+" ");
}
}
}
Problem: Write a program to find the second largest element in an array without sorting it.
Example: Input: `[3, 5, 2, 4, 1]` → Output: `4`
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//declaring all variables
int[] arr={3,5,2,4,1};
int largest=Integer.MIN_VALUE,secondlargest=Integer.MIN_VALUE;
//printing the array
System.out.println("The Array : ");
for(int num : arr)
{
System.out.print(num+" ");
}
//finding the second largest element
for(int num : arr)
{
if(num>largest)
{
secondlargest=largest;
largest=num;
}
else if(num>secondlargest && num!=largest)
{
secondlargest=num;
}
}
//printing output
System.out.println("\nSecond Largest Element : "+secondlargest);
}
}
Problem: Given a sorted array, remove the duplicates in place such that each element appears only once.
Example: Input: `[1, 1, 2, 2, 3, 4, 4, 5]` → Output: `[1, 2, 3, 4, 5]`
CODE :
import java.io.*;
class Main {
public static void main(String[] args) {
//declaring all variables
int i,index=0;
int[] arr={1,1,2,2,3,4,4,5};
//removing duplicates
for (i=1;i<arr.length;i++) {
if (arr[i]!=arr[index]) {
index++;
arr[index]=arr[i];
}
}
//printing output
System.out.println("Array without duplicates:");
for (i = 0; i <= index; i++) {
System.out.print(arr[i] + " ");
}
}
}
Problem: Write a program to find all pairs in an array that sum up to a given target.
Example: Input: `[1, 2, 3, 4, 5]`, `target = 6` → Output: `[(1, 5), (2, 4)]`
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//declaring all variables
int i,j,target;
int[] arr={1,2,3,4,5};
//getting the target value
System.out.print("target = ");
target = sc.nextInt();
//finding the pairs
System.out.print("[");
for (i=0;i<arr.length;i++) {
for (j=i+1;j<arr.length;j++) {
if (arr[i]+arr[j]==target) {
System.out.print("(" + arr[i] + ", " + arr[j] + "),");
}
}
}
System.out.println("]");
}
}
Problem: An array of `n-1` numbers is given, where numbers are in the range from `1` to `n`. Find the missing number.
Example: Input: `[1, 2, 4, 5, 6]` → Output: `3`
- Hint: Calculate the sum of `1` to `n` and subtract the sum of array elements from it.
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//declaring the variables
int[] arr = {1,2,4,5,6};
int n = arr.length+1;
int totalSum = n*(n+1)/2;
int arraySum = 0;
//finding the sum of elements present
for (int num : arr) {
arraySum += num;
}
//printing the missing number
System.out.println(totalSum-arraySum);
}
}
Problem: An element is considered a majority element if it appears more than `n/2` times in an array. Write a program to find the majority element, or return `None` if there isn’t one.
Example: Input: `[3, 3, 4, 2, 3, 3, 3]` → Output: `3`
(Based on the Boyre-Moore Voting Algorithm)
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//declaring the variables
//candidate stores the potential majority element
//count tracks "votes" for current candidate
int count=0,candidate=-1;
int[] arr = {3,3,4,2,3,3,3};
//first pass to identify the candidate
for (int num : arr) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
//second pass to verify the candidate
count = 0;
for (int num : arr) {
if (num == candidate) {
count++;
}
}
//printing the output after checking for majority condition
if (count > arr.length/2) {
System.out.println(candidate);
} else {
System.out.println("No Majority Element");
}
}
}
Problem: Given an array, move all zeros to the end while maintaining the relative order of other elements.
Example: Input: `[0, 1, 0, 3, 12]` → Output: `[1, 3, 12, 0, 0]`
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//declaring the variables
int[] arr = {0,1,0,3,12};
int index = 0;
//moving non-zero elements to the front
for (int num : arr) {
if (num != 0) {
arr[index++] = num;
}
}
//filling the remaining spaces with 0
while (index < arr.length) {
arr[index++] = 0;
}
//printing output array
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Problem: Write a program to check if a given array is sorted in ascending order.
Example: Input: `[1, 2, 3, 4, 5]` → Output: `True`, Input: `[1, 3, 2]` → Output: `False`
Hint: Use a loop to compare each element with the next one. Break the loop if any element is greater than the following one.
CODE :
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//declaring the variables
int[] arr = {1,2,3,4,5};
//try for [1,3,2] or for [-5,-4,-3,-2,-1]
boolean isSorted = true;
//performing calculations
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
isSorted = false;
break;
}
}
//printing the output
System.out.println(isSorted);
}
}
Problem: Write a program that takes two arrays and returns an array containing their intersection (the common elements). Each element in the result should be unique.
Example:
- Input: `array1 = [1, 2, 2, 1]` and `array2 = [2, 2]` → Output: `[2]`
- Input: `array1 = [4, 9, 5]` and `array2 = [9, 4, 9, 8, 4]` → Output: `[4, 9]`
Hint: Use a set to store elements from one array, then iterate through the second array to check for common elements, ensuring uniqueness in the result.
CODE :
import java.io.*;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//declaring the variables
int i,j;
int[] arr1 = {4,9,5};
int[] arr2 = {9,4,9,8,4};
//to prevent duplicates
boolean[] visited = new boolean[arr2.length];
//finding intersection of the two arrays
for (i = 0; i < arr1.length; i++) {
for (j = 0; j < arr2.length; j++) {
//checking for intersection and ensuring no duplicates
if (arr1[i] == arr2[j] && !visited[j]) {
System.out.print(arr1[i] + " ");
//marking the element as visited to avoid duplicates
visited[j] = true;
break;
}
}
}
}
}
Lessons To Deepen Connection And Communi...
A collection of insights that help us navigate relationships with clarity, empathy, and presence
Read More
Mental Models To Reframe Your Inner Worl...
A collection of ideas that enhance how we understand ourselves, navigate our emotions, and grow through life’s complexities
Read More
Mindset Shifts To Rewire How You Work An...
A collection of mindset shifts that act as gentle rewirings of how we approach productivity and cultivate meaningful impact
Read More