P3A Maximum distance between two occurrences of the same element in an array.

Given an array with repeated elements, the task is to find the maximum distance between two occurrences of an element.

Yogita Misal
1 min readAug 9, 2023

Solution:

A simple solution for this problem is to , one by one, pick each element from the Array and find it’s first and last occurrence for maximum distance.

Below is the implementation of this problem:




#include <bits/stdc++.h>

int maxDistance(int arr[], int n)
{


    int maxD = -1;
    for (int i = 0; i < n - 1; i++)
        for (int j = i + 1; j < n; j++)



            if (arr[i] == arr[j]) {
                int temp = abs(j - i);
                maxD = maxD > temp ? maxD : temp;
            }
    return maxD;
}
int main()
{
    int Arr[] = { 1, 2, 4, 1, 3, 4, 2, 5, 6, 5 };
    printf("Maximum distance between two occurrences of "
        "same element in array:%d",
        maxDistance(Arr, 10));
    return 0;
}

The time complexity: O(n^2)

An efficient solution to this problem is to use Hashing.


#include <bits/stdc++.h>

int maxDistance(int arr[], int n)

{

int maxD = -1;

for (int i = 0; i < n - 1; i++)

for (int j = i + 1; j < n; j++)





if (arr[i] == arr[j]) {



int temp = abs(j - i);

maxD = maxD > temp ? maxD : temp;

}

return maxD;

}



int main()

{

int Arr[] = { 1, 2, 4, 1, 3, 4, 2, 5, 6, 5 };

printf("Maximum distance between two occurrences of "

"same element in array:%d",

maxDistance(Arr, 10));

return 0;

}




#DSA

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Yogita Misal
Yogita Misal

No responses yet

Write a response