Given an array of N integers, write a program that prints the length of the longest subarray such that adjacent elements of the subarray have at least one digit in common.
Input : 12 23 45 43 36 97 Output : 3 Explanation: The subarray is 45 43 36 which has 4 common in 45, 43 and 3 common in 43, 36. Input : 11 22 33 44 54 56 63 Output : 4 Explanation: Subarray is 44, 54, 56, 63
A normal approach will be to check for all the subarrays possible. But the time complexity will be O(n2).
An efficient approach will be to create a hash[n] array which marks the occurrence of digits in the i-th index number. We iterate for every element and check if adjacent elements have a digit common in between. If they have a common digit, we keep the count of the length. If the adjacent elements do not have a digit in common, we initialize the count to zero and start counting again for a subarray. Print the maximum count which is obtained while iteration. We use a hash array to minimize the time complexity as the number can be of range 10^18 which will take 18 iterations in worst case.
Given below is the illustration of the above approach:
Time Complexity: O(n*10)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Longest subarray such that adjacent elements have at least one common digit | Set - 2
- Longest subsequence such that adjacent elements have at least one common digit
- Longest common subarray in the given two arrays
- Longest Subsequence with at least one common digit in every element
- Maximum length subarray with difference between adjacent elements as either 0 or 1
- Longest subarray with all elements same
- Length of the longest subsequence such that xor of adjacent elements is non-decreasing
- Longest subarray not having more than K distinct elements
- Length of the longest Subarray with only Even Elements
- Longest subarray in which all elements are greater than K
- Longest Subarray having sum of elements atmost 'k'
- Longest subarray with elements having equal modulo K
- Length of Longest Subarray with same elements in atmost K increments
- Length of longest Subarray with equal number of odd and even elements
- Longest subarray with absolute difference between elements less than or equal to K using Heaps
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.