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)
- 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 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 not having more than K distinct elements
- Longest subarray in which all elements are greater than K
- Length of the longest Subarray with only Even Elements
- Longest Subarray having sum of elements atmost 'k'
- Longest subarray with elements having equal modulo K
- Maximum length subsequence such that adjacent elements in the subsequence have a common factor
- Length of longest subarray in which elements greater than K are more than elements not greater than K
- Arrange N elements in circular fashion such that all elements are strictly less than sum of adjacent elements
- Maximize the subarray sum after multiplying all elements of any subarray with X
- Count divisors of n that have at-least one digit common with n
- Count pairs in an array which have at least one digit common
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.