Arrays Problems GFG
Arrays Problems GFG
Insertion is a basic but frequently used operation. Arrays in most languages can
not be dynamically shrinked or expanded. Here, we will work with such arrays and
try to insert an element at the end of the array.
You are given an array arr. The size of the array is given by sizeOfArray. You need to
insert an element at the end.
Array already have the sizeofarray -1 elements.
class Insert
// elements.
You are given an array arr(0-based index). The size of the array is given by
sizeOfArray. You need to insert an element at given index.
class Solution
// elements.
arr[index] = element;
Maximum Index
n=9
Output:
Explanation:
In the given array a[1] < a[7] satisfying the required condition(a[i] < a[j]) thus
giving the maximum difference of j - i which is 6(7-1).
class Solution{
// N: size of array
// Create arrays to store the minimum from the left and maximum from the rig
rightMax[n-1]= arr[n-1];
int i = 0, j = 0;
j++;
i++;
return maxDist;
Given an array arr[] of size N of positive integers which may have duplicates. The
task is to find the maximum and second maximum from the array, and both of them
should be different from each other, so If no second max exists, then the second max will
be -1.
class Solution{
{
//code here.
secondMax = max;
max = arr[i];
secondMax = arr[i];
if (secondMax == Integer.MIN_VALUE) {
secondMax = -1;
result.add(max);
result.add(secondMax);
return result;
Given an array a[ ] of size N. The task is to find the median and mean of the array
elements. Mean is average of the numbers and median is the element which is
smaller than half of the elements and greater than remaining half. If there are odd
elements, the median is simply the middle element in the sorted array. If there are
even elements, then the median is floor of average of two middle numbers in the
sorted array. If mean is floating point number, then we need to print floor of it.
Note: To find the median, you might need to sort the array. Since sorting is covered in
later tracks, we have already provided the sort function to you in the code.
class Solution
Arrays.sort(A);
if (N % 2 != 0) {
return A[N / 2]; // Return the middle element
} else {
int sum = 0;
sum += num;
// Return the mean, which is the sum divided by the number of elements
return sum / N;
class Solution{
rotationPoint = i + 1;
break;
return false;
}
return true;
return false;
return true;
Note: If at any instance, there are no more subarrays of size greater than or equal to
K, then reverse the last subarray (irrespective of its size). You shouldn't return any
array, modify the given array in-place.
class Solution {
// code here
arr.set(left, arr.get(right));
arr.set(right, temp);
left++;
right--;
}
}
Given an array arr[] of size N where every element is in the range from 0 to n-1.
Rearrange the given array so that the transformed array arrT[i] becomes arr[arr[i]].
NOTE: arr and arrT are both same variables, representing the array before and after
transformation respectively.
class Solution
// n: size of array
arr[i] += (arr[(int)arr[i]] % n) * n;
Rotate Array
Given an unsorted array arr[] of size n. Rotate the array to the left (counter-
clockwise direction) by d steps, where d is a positive integer.
class Solution {
d = d % n;
reverse(arr, 0, n - 1);
reverse(arr, 0, n - d - 1);
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
Leaders in an array
Given an array arr[] of n positive integers. Your task is to find the leaders in the
array. An element of the array is a leader if it is greater than all the elements to its right side or if it
is equal to the maximum element on its right side. The rightmost element is always a leader.
class Solution {
leaders.add(maxFromRight);
// Traverse the array from the second last element to the first element
maxFromRight = arr[i];
leaders.add(maxFromRight);
Collections.reverse(leaders);
return leaders;
Given a sorted array of positive integers. Your task is to rearrange the array elements alternatively
i.e first element should be max value, second should be min value, third should be second max,
fourth should be second min and so on.
Note: Modify the original array itself. Do it without using any extra space. You do not have to return
anything.
class Solution{
// temp: input array
// n: size of array
int maxIdx = n - 1;
int minIdx = 0;
if (i % 2 == 0) {
maxIdx--;
} else {
minIdx++;
}
}
arr[i] /= maxElem;
You are given an array arr[] of N integers. The task is to find the smallest positive
number missing from the array.
class Solution
//Function to find the smallest positive number missing from the array.
// While the current number is in the range [1, n] and it's not in its correct
position
arr[arr[i] - 1] = arr[i];
arr[i] = temp;
if (arr[i] != i + 1) {
return i + 1;
return n + 1;
Given an array arr[] of N positive integers which can contain integers from 1 to P
where elements can be repeated or can be absent from the array. Your task is to
count the frequency of all numbers from 1 to N. Make in-place changes in arr[], such
that arr[i] = frequency(i). Assume 1-based indexing.
Note: The elements greater than N in the array can be ignored for counting and do
modify the array in-place
int j = arr[i] - 1;
if (arr[j] <= 0) {
} else {
arr[j] = arr[i];
arr[i] = temp;
// If arr[i] is greater than N, mark arr[i] as visited and move to the next element
arr[i] = 0;
i++;
}
// If arr[i] is less than or equal to 0, move to the next element
else {
i++;
arr[i] = -arr[i];
The cost of stock on each day is given in an array A[] of size N. Find all the segments
of days on which you buy and sell the stock such that the sum of difference
between sell and buy prices is maximized. Each segment consists of indexes of two
elements, first is index of day on which you buy stock and second is index of day on
which you sell stock.
Note: Since there can be multiple solutions, the driver code will print 1 if your
answer is correct, otherwise, it will return 0. In case there's no profit the driver
code will print the string "No Profit" for a correct solution.
class Solution{
//Function to find the days of buying and selling stock for max profit.
// code here
// Create an ArrayList to store the segments where buy and sell occur
int sell = 0;
sell = i;
} else {
// If the current price is not greater than the previous price, it's time to sell
segment.add(buy);
segment.add(sell);
segments.add(segment);
buy = i;
sell = i;
}
// If there are segments left after traversing the array, add the last segment
segment.add(buy);
segment.add(sell);
segments.add(segment);
return segments;
class Solution{
// n: size of array
if (n <= 2) return 0; // No water can be trapped if there are less than 3 blocks
// Arrays to store the maximum heights to the left and right of each block
leftMax[0] = arr[0];
long totalWater = 0;
return totalWater;
}
}
Kadane's Algorithm
class Solution{
// n: size of array
}
// Return the maximum sum of the contiguous subarray found
return maxSoFar;
Given an array arr[] of N integers arranged in a circular fashion. Your task is to find
the maximum contiguous subarray sum.
class Solution{
// a: input array
// n: size of array
// Step 1: Find the maximum subarray sum using standard Kadane's algorithm
// Step 2: Find the sum of the array and the minimum subarray sum
int arraySum = 0;
a[i] = -a[i]; // Invert the elements for finding the minimum subarray sum
// Step 3: Find the minimum subarray sum using Kadane's algorithm on inverted
array
if (maxCircular == 0) {
return maxKadane;
return maxSoFar;
Given an array Arr of n integers arranged in a circular fashion. Your task is to find the
minimum absolute difference between adjacent elements.
class Solution{
// n: size of array
// Traverse the array and calculate the difference between adjacent elements
minDiff = diff;
}
// Also check the difference between the last and the first element (circular
nature)
minDiff = circularDiff;
return minDiff;
Wave Array
Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array(In
Place).
In other words, arrange the elements into a sequence such that arr[1] >= arr[2] <=
arr[3] >= arr[4] <= arr[5].....
Note:The given array is sorted in ascending order, and you don't need to return
anything to make changes in the original array itself.
class Solution {
// code here
for (int i = 0; i < n - 1; i += 2) {
a[i + 1] = temp;
Given n integer ranges, the task is to return the maximum occurring integer in the given
ranges. If more than one such integer exists, return the smallest one.
The ranges are in two arrays l[] and r[]. l[i] consists of the starting point of the range
and r[i] consists of the corresponding endpoint of the range & a maxx which is the
maximum value of r[].
// n : size of array
class Solution {
public static int maxOccured(int n, int l[], int r[], int maxx) {
// Step 1: Initialize the frequency array
freq[l[i]]++;
freq[r[i] + 1]--;
// Step 3: Compute the prefix sums to get the number of ranges covering each integer
int maxOccurred = 0;
maxCount = freq[i];
maxOccurred = i;
return maxOccurred;
}
Given an array arr[] of size N and two elements x and y, use counter variables to find
which element appears most in the array. If both elements have the same
frequency, then return the smaller element.
Note: We need to return the element, not its count.
class Solution {
// array.
// code here
int countX = 0;
int countY = 0;
if (arr[i] == x) {
countX++;
} else if (arr[i] == y) {
countY++;
return x;
return y;
} else {
return x < y ? x : y;
Fraction Trouble
Consider the set of irreducible fractions A = {n/d | n≤d and d and gcd(n,d) = 1}.You
are given a member of this set and your task is to find the largest fraction in this set
less than the given fraction.
Note: this is a set and so all the members are unique
You are given an array of size n. Find the maximum possible length of a subarray such
that its elements are arranged alternately either as even and odd or odd and even .
class Solution
// n: size of array
//Function to find the length of longest subarray of even and odd numbers.
public static int maxEvenOdd(int arr[], int n)
if (n == 0)
return 0;
int maxlength = 0; // This will store the maximum length found so far.
// Check if the current element has a different parity than the previous one.
if (arr[i] % 2 != prevodd) {
} else {
maxlength = currlength;
// Update the parity of the previous element to the current element's parity.
prevodd = arr[i] % 2;
return maxlength;
Equilibrium Point
Given an array A of n non negative numbers. The task is to find the first equilibrium
point in an array. Equilibrium point in an array is an index (or position) such that the
sum of all elements before that index is same as sum of elements after it.
Note: Return equilibrium point in 1-based indexing. Return -1 if no such point exists.
class Solution {
// a: input array
// n: size of array
long totalSum = 0;
totalSum += arr[i];
long leftSum = 0;
if (leftSum == rightSum) {
return i + 1;
leftSum += arr[i];
return -1;