Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the element with the longest distance in a given array where each element appears twice?

Given an array of int, each int appears exactly TWICE in the array. find and return the int such that this pair of int has the max distance between each other in this array.

e.g. [2, 1, 1, 3, 2, 3]

2: d = 5-1 = 4;
1: d = 3-2 = 1;
3: d = 6-4 = 2;
return 2

My ideas:

Use hashmap, key is the a[i], and value is the index. Scan the a[], put each number into hash. If a number is hit twice, use its index minus the old numbers index and use the result to update the element value in hash.

After that, scan hash and return the key with largest element (distance). it is O(n) in time and space.

How to do it in O(n) time and O(1) space ?

like image 314
user1002288 Avatar asked Dec 16 '11 07:12

user1002288


People also ask

How do you check if an element appears twice in an array?

Multiply the array element at that given value (index) with a negative number say -1. If a number have appeared once then the value in the array at that index will be negative else it will be positive if it has appeared twice (-1 * -1 = 1). Find the element with positive value and return their index.

How do you find the maximum distance between two elements in an array?

A simple solution for this problem is to, one by one, pick each element from the array and find its first and last occurrence in the array and take the difference between the first and last occurrence for maximum distance.

How do you find the maximum occurrence of an element in an array?

Navigate the array. Update the array as for ith index :- arrA[arrA[i]% n] = arrA[arrA[i]% n] + n; Now navigate the updated array and check which index has the maximum value, that index number is the element which has the maximum occurrence in the array.

Which method is based on the maximum distance between the two elements?

The function maxDistance( int arr[],int n) is used to calculate the Maximum distance between two occurrences of the same element. We initialize the variable maxD with -1.


1 Answers

You would like to have the maximal distance, so I assume the number you search a more likely to be at the start and the end. This is why I would loop over the array from start and end at the same time.

[2, 1, 1, 3, 2, 3]
Check if 2 == 3?
Store a map of numbers and position: [2 => 1, 3 => 6]
Check if 1 or 2 is in [2 => 1, 3 => 6] ?

I know, that is not even pseudo code and not complete but just to give out the idea.

like image 193
PiTheNumber Avatar answered Oct 04 '22 05:10

PiTheNumber