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 email@example.com. 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Rearrange the array to maximize the number of primes in prefix sum of the array
- Count the number of primes in the prefix sum array of the given array
- Longest Common Prefix Matching | Set-6
- Longest Common Prefix using Trie
- Longest prefix in a string with highest frequency
- Length of longest Powerful number subsequence in an Array
- Length of Longest Perfect number Subsequence in an Array
- Longest sub-array with equal number of alphabets and numeric characters
- Longest Common Prefix using Character by Character Matching
- Longest Common Prefix using Word by Word Matching
- Longest string which is prefix string of at least two strings
- Prefix Sum of Matrix (Or 2D Array)
- Prefix Product Array
- Maximize the sum of array after multiplying a prefix and suffix by -1
- Prefix sum array in Python using accumulate function
- Maximum array sum with prefix and suffix multiplications with -1 allowed
- Index with Minimum sum of prefix and suffix sums in an Array
- Prefix Sum Array - Implementation and Applications in Competitive Programming
- Number of prefix sum prime in given range query
- Longest alternating sub-array starting from every index in a Binary Array