Longest subarray such that adjacent elements have at least one common digit | Set 1
Last Updated :
11 Jul, 2025
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.
Examples:
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][10] 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 the worst case.
Steps to solve this problem:
1. Create an array hash. hash is an 2-dimensional array with n rows and 10 columns, where each row represents the presence of each digit (0 to 9) in the corresponding index of the input array a.
2. Initialize hash to all zeros.
3. Loop through the elements of the input array a. For each element, extract the digits from the number by repeatedly dividing the number by 10 until it becomes zero, and mark the corresponding digit in the corresponding row of hash as 1.
4. Initialize longest to the minimum integer value and count to 0.
5. Loop through the elements of the input array a and check for every two consecutive elements. If they have at least one digit in common, increment the count by 1. If they don't have any digit in common, update longest to the maximum of longest and count + 1, and reset count to 0.
6. After the loop, update longest to the maximum of longest and count + 1.
7. Return longest.
Given below is the illustration of the above approach:
C++
// CPP program to print the length of the
// longest subarray such that adjacent elements
// of the subarray have at least one digit in
// common.
#include <bits/stdc++.h>
using namespace std;
// function to print the longest subarray
// such that adjacent elements have at least
// one digit in common
int longestSubarray(int a[], int n)
{
// remembers the occurrence of digits in
// i-th index number
int hash[n][10];
memset(hash, 0, sizeof(hash));
// marks the presence of digit in i-th
// index number
for (int i = 0; i < n; i++) {
int num = a[i];
while (num) {
// marks the digit
hash[i][num % 10] = 1;
num /= 10;
}
}
// counts the longest Subarray
int longest = INT_MIN;
// counts the subarray
int count = 0;
// check for all adjacent elements
for (int i = 0; i < n - 1; i++) {
int j;
for (j = 0; j < 10; j++) {
// if adjacent elements have digit j
// in them count and break as we have
// got at-least one digit
if (hash[i][j] and hash[i + 1][j]) {
count++;
break;
}
}
// if no digits are common
if (j == 10) {
longest = max(longest, count + 1);
count = 0;
}
}
longest = max(longest, count + 1);
// returns the length of the longest subarray
return longest;
}
// Driver Code
int main()
{
int a[] = { 11, 22, 33, 44, 54, 56, 63 };
int n = sizeof(a) / sizeof(a[0]);
// function call
cout << longestSubarray(a, n);
return 0;
}
Java
// Java program to print the length of the
// longest subarray such that adjacent elements
// of the subarray have at least one digit in
// common.
class GFG {
// function to print the longest subarray
// such that adjacent elements have at least
// one digit in common
static int longestSubarray(int a[], int n) {
// remembers the occurrence of digits in
// i-th index number
int hash[][] = new int[n][10];
// marks the presence of digit in i-th
// index number
for (int i = 0; i < n; i++) {
int num = a[i];
while (num != 0) {
// marks the digit
hash[i][num % 10] = 1;
num /= 10;
}
}
// counts the longest Subarray
int longest = Integer.MIN_VALUE;
// counts the subarray
int count = 0;
// check for all adjacent elements
for (int i = 0; i < n - 1; i++) {
int j;
for (j = 0; j < 10; j++) {
// if adjacent elements have digit j
// in them count and break as we have
// got at-least one digit
if (hash[i][j] == 1 & hash[i + 1][j] == 1) {
count++;
break;
}
}
// if no digits are common
if (j == 10) {
longest = Math.max(longest, count + 1);
count = 0;
}
}
longest = Math.max(longest, count + 1);
// returns the length of the longest subarray
return longest;
}
// Driver Code
public static void main(String[] args) {
int a[] = {11, 22, 33, 44, 54, 56, 63};
int n = a.length;
// function call
System.out.println(longestSubarray(a, n));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python 3 program to print the length of the
# longest subarray such that adjacent elements
# of the subarray have at least one digit in
# common.
import sys
# function to print the longest subarray
# such that adjacent elements have at least
# one digit in common
def longestSubarray(a, n):
# remembers the occurrence of digits
# in i-th index number
hash = [[0 for i in range(10)]
for j in range(n)]
# marks the presence of digit in
# i-th index number
for i in range(n):
num = a[i]
while (num):
# marks the digit
hash[i][num % 10] = 1
num = int(num / 10)
# counts the longest Subarray
longest = -sys.maxsize-1
# counts the subarray
count = 0
# check for all adjacent elements
for i in range(n - 1):
for j in range(10):
# if adjacent elements have digit j
# in them count and break as we have
# got at-least one digit
if (hash[i][j] and hash[i + 1][j]):
count += 1
break
# if no digits are common
if (j == 10):
longest = max(longest, count + 1)
count = 0
longest = max(longest, count + 1)
# returns the length of the longest
# subarray
return longest
# Driver Code
if __name__ == '__main__':
a = [11, 22, 33, 44, 54, 56, 63]
n = len(a)
# function call
print(longestSubarray(a, n))
# This code is contributed by
# Sanjit_Prasad
C#
// C# program to print the length of the
// longest subarray such that adjacent elements
// of the subarray have at least one digit in
// common.
using System;
public class GFG {
// function to print the longest subarray
// such that adjacent elements have at least
// one digit in common
static int longestSubarray(int []a, int n) {
// remembers the occurrence of digits in
// i-th index number
int [,]hash = new int[n,10];
// marks the presence of digit in i-th
// index number
for (int i = 0; i < n; i++) {
int num = a[i];
while (num != 0) {
// marks the digit
hash[i,num % 10] = 1;
num /= 10;
}
}
// counts the longest Subarray
int longest = int.MinValue;
// counts the subarray
int count = 0;
// check for all adjacent elements
for (int i = 0; i < n - 1; i++) {
int j;
for (j = 0; j < 10; j++) {
// if adjacent elements have digit j
// in them count and break as we have
// got at-least one digit
if (hash[i,j] == 1 & hash[i + 1,j] == 1) {
count++;
break;
}
}
// if no digits are common
if (j == 10) {
longest = Math.Max(longest, count + 1);
count = 0;
}
}
longest = Math.Max(longest, count + 1);
// returns the length of the longest subarray
return longest;
}
// Driver Code
public static void Main() {
int []a = {11, 22, 33, 44, 54, 56, 63};
int n = a.Length;
// function call
Console.Write(longestSubarray(a, n));
}
}
// This code is contributed by Rajput-Ji//
PHP
<?php
// PHP program to print the length of the
// longest subarray such that adjacent
// elements of the subarray have at least
// one digit in common.
// function to print the longest subarray
// such that adjacent elements have at
// least one digit in common
function longestSubarray(&$a, $n)
{
// remembers the occurrence of
// digits in i-th index number
$hash = array_fill(0, $n,
array_fill(0, 10, NULL));
// marks the presence of digit in
// i-th index number
for ($i = 0; $i < $n; $i++)
{
$num = $a[$i];
while ($num)
{
// marks the digit
$hash[$i][$num % 10] = 1;
$num = intval($num / 10);
}
}
// counts the longest Subarray
$longest = PHP_INT_MIN;
// counts the subarray
$count = 0;
// check for all adjacent elements
for ($i = 0; $i < $n - 1; $i++)
{
for ($j = 0; $j < 10; $j++)
{
// if adjacent elements have digit j
// in them count and break as we have
// got at-least one digit
if ($hash[$i][$j] and $hash[$i + 1][$j])
{
$count++;
break;
}
}
// if no digits are common
if ($j == 10)
{
$longest = max($longest, $count + 1);
$count = 0;
}
}
$longest = max($longest, $count + 1);
// returns the length of the
// longest subarray
return $longest;
}
// Driver Code
$a = array(11, 22, 33, 44, 54, 56, 63 );
$n = sizeof($a);
// function call
echo longestSubarray($a, $n);
// This code is contributed by ChitraNayal
?>
JavaScript
<script>
// Javascript program to print the length of the
// longest subarray such that adjacent elements
// of the subarray have at least one digit in
// common.
// function to print the longest subarray
// such that adjacent elements have at least
// one digit in common
function longestSubarray(a,n)
{
// remembers the occurrence of digits in
// i-th index number
let hash = new Array(n);
for(let i=0;i<n;i++)
{
hash[i]=new Array(10);
for(let j=0;j<10;j++)
{
hash[i][j]=0;
}
}
// marks the presence of digit in i-th
// index number
for (let i = 0; i < n; i++) {
let num = a[i];
while (num != 0) {
// marks the digit
hash[i][num % 10] = 1;
num = Math.floor(num/ 10);
}
}
// counts the longest Subarray
let longest = Number.MIN_VALUE;
// counts the subarray
let count = 0;
// check for all adjacent elements
for (let i = 0; i < n - 1; i++) {
let j;
for (j = 0; j < 10; j++) {
// if adjacent elements have digit j
// in them count and break as we have
// got at-least one digit
if (hash[i][j] == 1 & hash[i + 1][j] == 1) {
count++;
break;
}
}
// if no digits are common
if (j == 10) {
longest = Math.max(longest, count + 1);
count = 0;
}
}
longest = Math.max(longest, count + 1);
// returns the length of the longest subarray
return longest;
}
// Driver Code
let a=[11, 22, 33, 44, 54, 56, 63];
let n = a.length;
// function call
document.write(longestSubarray(a, n));
// This code is contributed by rag2127
</script>
Time Complexity: O(n*10)
Longest subarray such that adjacent elements have at least one common digit | Set – 2
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem