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.
Input : array = [7, 42, 5, 6, 42, 8, 7, 5, 3, 6, 7] X = 7 Y = 42 Output : 9 The longest prefix with same number of occurrences of 7 and 42 is: 7, 42, 5, 6, 42, 8, 7, 5, 3, 6 42
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.
Below is the implementation of above idea :
Ending index of prefix is 9
Time complexity : O(n)
This article is contributed by Niteesh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Given an array A and a number x, check for pair in A with sum as x
- Find the Number Occurring Odd Number of Times
- Find the Missing Number
- Search an element in a sorted and rotated array
- Merge an array of size n into another array of size m+n
- k largest(or smallest) elements in an array | added Min Heap method
- Program for array rotation
- Write a program to reverse an array or string
- Reversal algorithm for array rotation
- Block swap algorithm for array rotation
- Leaders in an array
- Count Inversions in an array | Set 1 (Using Merge Sort)
- Find the smallest and second smallest elements in an array
- Maximum and minimum of an array using minimum number of comparisons
- Check for Majority Element in a sorted array