Longest prefix that contains same number of X and Y in an array - GeeksforGeeks
Given two positive integers X and Y, and an array arr[] of positive integers. We need to find the longest prefix index which contains an equal number of X and Y. Print the maximum index of largest prefix if exist otherwise print -1.
Read full article from Longest prefix that contains same number of X and Y in an array - GeeksforGeeks
Given two positive integers X and Y, and an array arr[] of positive integers. We need to find the longest prefix index which contains an equal number of X and Y. Print the maximum index of largest prefix if exist otherwise print -1.
We start from the index 0 and run a loop till the end of array. We keep increasing counters for both numbers X and Y. After iterating over the whole array, the last index when counts of X and y were equal is our result.
int
findIndex(
int
arr[],
int
X,
int
Y,
int
n)
{
// counters for X and Y
int
nx = 0,ny = 0;
int
result = -1;
for
(
int
i=0; i<n; i++)
{
// If value is equal to X increment counter of X
if
(arr[i]==X)
nx++;
// If value is equal to X increment counter of X
if
(arr[i]==Y)
ny++;
// If counters are equal(but not zero) save
// the result as i
if
((nx==ny) && (nx!=0 && ny!=0))
result = i;
}
return
result;
}