ARRAYS PROBLEMS GFG
Array insert at end
BasicAccuracy: 87.65%Submissions: 51K+Points: 1
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
// You only need to insert the given element at
// the end, i.e., at index sizeOfArray - 1. You may
// assume that the array already has sizeOfArray - 1
// elements.
public void insertAtEnd(int arr[],int sizeOfArray,int element)
//Your code here
arr[sizeOfArray -1] = element;
Array insert at index
BasicAccuracy: 44.81%Submissions: 92K+Points: 1
Insertion is a basic but frequently used operation. Arrays in most languages
cannnot be dynamically shrinked or expanded. Here, we will work with such arrays
and try to insert an element at some index.
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.
//Complete this function, Geeks
class Solution
// You need to insert the given element at the given index.
// After inserting the elements at index, elements
// from index onward should be shifted one position ahead
// You may assume that the array already has sizeOfArray - 1
// elements.
public void insertAtIndex(int arr[],int sizeOfArray,int index,int element)
//Your code here, Geeks
// Shift elements to the right from the end to the index
for (int i = sizeOfArray - 1; i > index; i--) {
arr[i] = arr[i - 1];
// Insert the element at the specified index
arr[index] = element;
Maximum Index
MediumAccuracy: 24.5%Submissions: 236K+Points: 4
Given an array a of n positive integers. The task is to find the maximum of j - i
subjected to the constraint of a[i] < a[j] and i < j.
Input:
n=9
a[] = {34, 8, 10, 3, 2, 80, 30, 33, 1}
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{
// A[]: input array
// N: size of array
// Function to find the maximum index difference.
static int maxIndexDiff(int arr[], int n) {
// Your code here
// Create arrays to store the minimum from the left and maximum from the rig
int []rightMax = new int[n];
rightMax[n-1]= arr[n-1];
for(int i = n-2; i>=0; i--)
rightMax[i] = [Link](rightMax[i+1] , arr[i]);
// rightMax[i] = max{ arr[i...(n-1] }
int maxDist = Integer.MIN_VALUE;
int i = 0, j = 0;
while(i < n && j < n)
{
if(rightMax[j] >= arr[i])
maxDist = [Link]( maxDist, j-i );
j++;
else // if(rightMax[j] < leftMin[i])
i++;
return maxDist;
Max and Second Max
EasyAccuracy: 41.08%Submissions: 91K+Points: 2
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{
// Function to find largest and second largest element in the array
public static ArrayList<Integer> largestAndSecondLargest(int sizeOfArray, int
arr[])
{
//code here.
ArrayList<Integer> result = new ArrayList<>();
// Initialize maximum and second maximum
int max = Integer.MIN_VALUE;
int secondMax = Integer.MIN_VALUE;
// Iterate through the array to find maximum and second maximum
for (int i = 0; i < sizeOfArray; i++) {
if (arr[i] > max) {
secondMax = max;
max = arr[i];
} else if (arr[i] > secondMax && arr[i] != max) {
secondMax = arr[i];
// Check if secondMax is still MIN_VALUE (no second max found)
if (secondMax == Integer.MIN_VALUE) {
secondMax = -1;
// Add maximum and second maximum to the result ArrayList
[Link](max);
[Link](secondMax);
return result;
Mean And Median of Array
EasyAccuracy: 44.05%Submissions: 74K+Points: 2
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
//Function to find median of the array elements.
public int median(int A[],int N)
[Link](A);
//Your code here
//If median is fraction then conver it to integer and return
// If the number of elements in the array is odd
if (N % 2 != 0) {
return A[N / 2]; // Return the middle element
} else {
// If the number of elements is even, return the floor of the average
// of the two middle elements
return (A[N / 2] + A[N / 2 - 1]) / 2;
//Function to find median of the array elements.
public int mean(int A[],int N)
//Your code here
int sum = 0;
// Calculate the sum of all elements in the array
for (int num : A) {
sum += num;
// Return the mean, which is the sum divided by the number of elements
return sum / N;
Check if array is sorted and rotated
MediumAccuracy: 26.04%Submissions: 52K+Points: 4
Given an array arr[] of N distinct integers, check if this array is Sorted (non-increasing or
non-decreasing) and Rotated counter-clockwise. Note that input array may be sorted
in either increasing or decreasing order, then rotated.
A sorted array is not considered as sorted and rotated, i.e., there should be at least
one rotation.
class Solution{
// arr[]: input array
// num: size of array
// Function to check if array is sorted and rotated
public static boolean checkRotatedAndSorted(int arr[], int num){
// Your code here
int rotationPoint = -1;
// Find the rotation point
for (int i = 0; i < num - 1; i++) {
if (arr[i] > arr[i + 1]) {
rotationPoint = i + 1;
break;
// If there is no rotation or if the array is not sorted after rotation
if (rotationPoint == -1 || !isSorted(arr, rotationPoint, num)) {
return false;
}
// Check if the array is rotated and sorted in non-increasing order
if (arr[num - 1] <= arr[0]) {
return true;
// Check if the array is rotated and sorted in non-decreasing order
return arr[num - 1] >= arr[0];
// Function to check if the array is sorted in increasing order
private static boolean isSorted(int[] arr, int start, int num) {
for (int i = start; i < num - 1 + start; i++) {
if (arr[i % num] > arr[(i + 1) % num]) {
return false;
return true;
Reverse array in groups
BasicAccuracy: 37.48%Submissions: 318K+Points: 1
Given an array arr[] of positive integers of size N. Reverse every sub-array group of
size K.
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 {
//Function to reverse every sub-array group of size k.
void reverseInGroups(ArrayList<Integer> arr, int n, int k) {
// code here
// Iterate through the array in groups of size k
for (int i = 0; i < n; i += k) {
int left = i; // Start index of the current group
int right = [Link](i + k - 1, n - 1); // End index of the current group
// Reverse the current group
while (left < right) {
// Swap elements at positions left and right
int temp = [Link](left);
[Link](left, [Link](right));
[Link](right, temp);
// Move towards the center of the group
left++;
right--;
}
}
Rearrange an array with O(1) extra space
MediumAccuracy: 56.34%Submissions: 112K+Points: 4
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
// arr: input array
// n: size of array
//Function to rearrange an array so that arr[i] becomes arr[arr[i]]
//with O(1) extra space.
static void arrange(long arr[], int n)
// your code here
// Step 1: Encode both old and new values at each index
for (int i = 0; i < n; i++) {
// arr[(int)arr[i]] % n gives the original value at the position arr[i]
// Multiplying it by n and adding it to arr[i] encodes the new value
arr[i] += (arr[(int)arr[i]] % n) * n;
// Step 2: Update the array with the new values
for (int i = 0; i < n; i++) {
arr[i] /= n; // Extract the new value by dividing by n
Rotate Array
EasyAccuracy: 37.06%Submissions: 320K+Points: 2
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 {
// Function to rotate an array by d elements in counter-clockwise direction.
static void rotateArr(int arr[], int d, int n) {
// add your code here
// Normalize d to ensure it is within the bounds of the array length
d = d % n;
if (d == 0) return; // No rotation needed if d is 0
// Step 1: Reverse the entire array
reverse(arr, 0, n - 1);
// Step 2: Reverse the first n - d elements
reverse(arr, 0, n - d - 1);
// Step 3: Reverse the last d elements
reverse(arr, n - d, n - 1);
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--;
Leaders in an array
EasyAccuracy: 29.94%Submissions: 648K+Points: 2
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 {
// Function to find the leaders in the array.
static ArrayList<Integer> leaders(int n, int arr[]){
// Your code here
// ArrayList to store leader elements
ArrayList<Integer> leaders = new ArrayList<>();
// Initialize the maximum element to the last element
int maxFromRight = arr[n - 1];
// Rightmost element is always a leader
[Link](maxFromRight);
// Traverse the array from the second last element to the first element
for (int i = n - 2; i >= 0; i--) {
if (arr[i] >= maxFromRight) {
maxFromRight = arr[i];
[Link](maxFromRight);
// Since we collected leaders in reverse order, we need to reverse the list
[Link](leaders);
return leaders;
Rearrange Array Alternately
MediumAccuracy: 35.15%Submissions: 234K+Points: 4
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
//Function to rearrange the array elements alternately.
public static void rearrange(long arr[], int n){
// Your code here
// Initialize pointers for maximum and minimum elements
int maxIdx = n - 1;
int minIdx = 0;
// The maximum element plus one (acting as a multiplier)
long maxElem = arr[maxIdx] + 1;
// Traverse the array
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
// Even index: place maximum element
arr[i] += (arr[maxIdx] % maxElem) * maxElem;
maxIdx--;
} else {
// Odd index: place minimum element
arr[i] += (arr[minIdx] % maxElem) * maxElem;
minIdx++;
}
}
// Decode the array to get the actual values
for (int i = 0; i < n; i++) {
arr[i] /= maxElem;
Smallest Positive missing number
MediumAccuracy: 25.13%Submissions: 324K+Points: 4
You are given an array arr[] of N integers. The task is to find the smallest positive
number missing from the array.
Note: Positive number starts from 1.
class Solution
//Function to find the smallest positive number missing from the array.
static int missingNumber(int arr[], int n)
// Your code here
// Step 1: Place each number in its right position
for (int i = 0; i < n; i++) {
// While the current number is in the range [1, n] and it's not in its correct
position
while (arr[i] > 0 && arr[i] <= n && arr[arr[i] - 1] != arr[i]) {
// Swap arr[i] with arr[arr[i] - 1]
int temp = arr[arr[i] - 1];
arr[arr[i] - 1] = arr[i];
arr[i] = temp;
// Step 2: Identify the first missing positive number
for (int i = 0; i < n; i++) {
if (arr[i] != i + 1) {
return i + 1;
// If all numbers from 1 to n are present, return n + 1
return n + 1;
Frequencies of Limited Range Array Elements
EasyAccuracy: 27.64%Submissions: 252K+Points: 2
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
// Iterate through the array
int i;
for (i = 0; i < N;) {
// If arr[i] is within the valid range [1, N]
if (arr[i] > 0 && arr[i] <= N) {
// Calculate the index j corresponding to the value arr[i]
int j = arr[i] - 1;
// If arr[j] is non-positive, decrease arr[i] and move to the next element
if (arr[j] <= 0) {
arr[i] = 0; // Mark arr[i] as visited
arr[j]--; // Decrement arr[j] to indicate occurrence of arr[i]
i++; // Move to the next element
} else {
// Swap arr[j] and arr[i] and mark arr[j] as visited
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
arr[j] = -1; // Mark arr[j] as visited
// If arr[i] is greater than N, mark arr[i] as visited and move to the next element
else if (arr[i] > N) {
arr[i] = 0;
i++;
}
// If arr[i] is less than or equal to 0, move to the next element
else {
i++;
// Convert the visited elements back to their original positive values
for (i = 0; i < N; i++) {
arr[i] = -arr[i];
Stock buy and sell
MediumAccuracy: 29.18%Submissions: 266K+Points: 4
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.
ArrayList<ArrayList<Integer> > stockBuySell(int A[], int n) {
// code here
// Create an ArrayList to store the segments where buy and sell occur
ArrayList<ArrayList<Integer>> segments = new ArrayList<>();
// Initialize variables to track buy and sell indices
int buy = 0;
int sell = 0;
// Traverse the array
for (int i = 1; i < n; i++) {
// If the current price is greater than the previous price, consider it as a
potential sell day
if (A[i] > A[i - 1]) {
// Update the sell index
sell = i;
} else {
// If the current price is not greater than the previous price, it's time to sell
if (sell > buy) {
// Add the segment to the list
ArrayList<Integer> segment = new ArrayList<>();
[Link](buy);
[Link](sell);
[Link](segment);
// Update the buy index
buy = i;
// Reset the sell index
sell = i;
}
// If there are segments left after traversing the array, add the last segment
if (sell > buy) {
ArrayList<Integer> segment = new ArrayList<>();
[Link](buy);
[Link](sell);
[Link](segment);
// Return the list of segments
return segments;
Trapping Rain Water
MediumAccuracy: 33.14%Submissions: 412K+Points: 4
Given an array arr[] of N non-negative integers representing the height of blocks. If
width of each block is 1, compute how much water can be trapped between the
blocks during the rainy season.
class Solution{
// arr: input array
// n: size of array
// Function to find the trapped water between the blocks.
static long trappingWater(int arr[], int n) {
// Your code here
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
int[] leftMax = new int[n];
int[] rightMax = new int[n];
// Fill leftMax array
leftMax[0] = arr[0];
for (int i = 1; i < n; i++) {
leftMax[i] = [Link](arr[i], leftMax[i - 1]);
// Fill rightMax array
rightMax[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--) {
rightMax[i] = [Link](arr[i], rightMax[i + 1]);
// Calculate the total trapped water
long totalWater = 0;
for (int i = 0; i < n; i++) {
totalWater += [Link](leftMax[i], rightMax[i]) - arr[i];
return totalWater;
}
}
Kadane's Algorithm
MediumAccuracy: 36.28%Submissions: 907K+Points: 4
Given an array arr[] of n integers. Find the contiguous sub-array(containing at least
one number) which has the maximum sum and return its sum.
class Solution{
// arr: input array
// n: size of array
//Function to find the sum of contiguous subarray with maximum sum.
long maxSubarraySum(int arr[], int n){
// Your code here
// Initialize variables to track the maximum sums
long maxSoFar = arr[0];
long maxEndingHere = arr[0];
// Traverse the array from the second element
for (int i = 1; i < n; i++) {
// Update maxEndingHere to include the current element or start a new
subarray
maxEndingHere = [Link](arr[i], maxEndingHere + arr[i]);
// Update maxSoFar to be the maximum value found so far
maxSoFar = [Link](maxSoFar, maxEndingHere);
}
// Return the maximum sum of the contiguous subarray found
return maxSoFar;
Max Circular Subarray Sum
HardAccuracy: 29.37%Submissions: 101K+Points: 8
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
//Function to find maximum circular subarray sum.
static int circularSubarraySum(int a[], int n) {
// Your code here
// Step 1: Find the maximum subarray sum using standard Kadane's algorithm
int maxKadane = kadane(a, n);
// Step 2: Find the sum of the array and the minimum subarray sum
int arraySum = 0;
for (int i = 0; i < n; i++) {
arraySum += a[i];
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
int maxInvertedKadane = kadane(a, n);
int maxCircular = arraySum + maxInvertedKadane; // Inverted back to positive
// Edge case: If all elements are negative
if (maxCircular == 0) {
return maxKadane;
// Step 4: Return the maximum of maxKadane and maxCircular
return [Link](maxKadane, maxCircular);
// Helper function to compute standard Kadane's algorithm
static int kadane(int a[], int n) {
int maxSoFar = a[0];
int maxEndingHere = a[0];
for (int i = 1; i < n; i++) {
maxEndingHere = [Link](a[i], maxEndingHere + a[i]);
maxSoFar = [Link](maxSoFar, maxEndingHere);
}
return maxSoFar;
Minimum adjacent difference in a circular array
EasyAccuracy: 68.68%Submissions: 30K+Points: 2
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{
//Function to find minimum adjacent difference in a circular array.
// arr[]: input array
// n: size of array
public static int minAdjDiff(int arr[], int n) {
// Your code here
// Initialize the minimum difference to a large value
int minDiff = Integer.MAX_VALUE;
// Traverse the array and calculate the difference between adjacent elements
for (int i = 0; i < n - 1; i++) {
int diff = [Link](arr[i] - arr[i + 1]);
if (diff < minDiff) {
minDiff = diff;
}
// Also check the difference between the last and the first element (circular
nature)
int circularDiff = [Link](arr[n - 1] - arr[0]);
if (circularDiff < minDiff) {
minDiff = circularDiff;
// Return the minimum difference found
return minDiff;
Wave Array
EasyAccuracy: 63.69%Submissions: 243K+Points: 2
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].....
If there are multiple solutions, find the lexicographically smallest one.
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 {
public static void convertToWave(int n, int[] a) {
// code here
for (int i = 0; i < n - 1; i += 2) {
// Swap a[i] and a[i+1]
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
Maximum occured integer
MediumAccuracy: 32.93%Submissions: 83K+Points: 4
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[].
For example, consider the following ranges.
l[] = {2, 1, 3}, r[] = {5, 3, 9}
Ranges represented by the above arrays are.
[2, 5] = {2, 3, 4, 5}
[1, 3] = {1, 2, 3}
[3, 9] = {3, 4, 5, 6, 7, 8, 9}
The maximum occurred integer in these ranges is 3.
// n : size of array
// maxx: maximum element in R[]
// arr[]: declared globally with size equal to 1000000
class Solution {
// Function to find the maximum occurred integer in all ranges.
public static int maxOccured(int n, int l[], int r[], int maxx) {
// Step 1: Initialize the frequency array
int[] freq = new int[maxx + 2];
// Step 2: Update the frequency array for each range
for (int i = 0; i < n; i++) {
freq[l[i]]++;
if (r[i] + 1 <= maxx) {
freq[r[i] + 1]--;
// Step 3: Compute the prefix sums to get the number of ranges covering each integer
int maxOccurred = 0;
int maxCount = freq[0];
for (int i = 1; i <= maxx; i++) {
freq[i] += freq[i - 1];
if (freq[i] > maxCount) {
maxCount = freq[i];
maxOccurred = i;
// Step 4: Return the maximum occurred integer
return maxOccurred;
}
Who has the majority?
BasicAccuracy: 44.36%Submissions: 91K+Points: 1
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 {
// Function to find element with more appearances between two elements in an
// array.
public int majorityWins(int arr[], int n, int x, int y) {
// code here
// Initialize counters for x and y
int countX = 0;
int countY = 0;
// Traverse the array to count occurrences of x and y
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
countX++;
} else if (arr[i] == y) {
countY++;
// Compare the counts
if (countX > countY) {
return x;
} else if (countY > countX) {
return y;
} else {
// If counts are equal, return the smaller element
return x < y ? x : y;
Fraction Trouble
Difficulty: MediumAccuracy: 59.14%Submissions: 5K+Points: 4
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
Longest Subarray Of Evens And Odds
MediumAccuracy: 59.21%Submissions: 27K+Points: 4
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 .
// User class to complete
class Solution
// arr[]: input array
// 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)
// Edge case: if the array is empty, return 0
if (n == 0)
return 0;
// Initialize variables to track maximum length of alternating subarray
// and current length of the alternating subarray being considered.
int maxlength = 0; // This will store the maximum length found so far.
int currlength = 1; // Initialize current length to 1 because the first element
itself is a valid subarray.
// Determine the parity (even or odd) of the first element.
int prevodd = arr[0] % 2; // 0 if arr[0] is even, 1 if arr[0] is odd
// Iterate through the array starting from the second element.
for (int i = 1; i < n; i++) {
// Check if the current element has a different parity than the previous one.
if (arr[i] % 2 != prevodd) {
currlength++; // If different, increment the current length of alternating
subarray.
} else {
currlength = 1; // If same, reset current length to 1 to start a new subarray.
// Update the maximum length found so far if current length is greater.
if (currlength > maxlength)
maxlength = currlength;
// Update the parity of the previous element to the current element's parity.
prevodd = arr[i] % 2;
// Return the maximum length of alternating subarray found.
return maxlength;
Equilibrium Point
EasyAccuracy: 28.13%Submissions: 556K+Points: 2
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
// Function to find equilibrium point in the array.
public static int equilibriumPoint(long arr[], int n) {
// Your code here
long totalSum = 0;
for (int i = 0; i < n; i++) {
totalSum += arr[i];
long leftSum = 0;
for (int i = 0; i < n; i++) {
// Calculate right sum as totalSum - leftSum - arr[i]
long rightSum = totalSum - leftSum - arr[i];
// Check if leftSum equals rightSum
if (leftSum == rightSum) {
// Return equilibrium point in 1-based indexing
return i + 1;
// Update leftSum by adding current element
leftSum += arr[i];
// If no equilibrium point found, return -1
return -1;