Longest sub-array with equal number of alphabets and numeric characters

Given an array of alphanumeric characters. The task is to find the longest contiguous sub-array which has equal numbers of letters (alphabets) and numbers (numeric digits). Print the starting and ending index of this sub-array. If there are multiple results, output the one with the lowest starting index.

Examples:

Input: arr[] = {‘A’, ‘B’, ‘X’, ‘4’, ‘6’, ‘X’, ‘a’}
Output: 1 4
The required sub-array is {‘B’, ‘X’, ‘4’, ‘6’}.
{‘X’, ‘4’, ‘6’, ‘X’} is also a valid sub-array of maximum
length but its starting index is not minimum.

Input: arr[] = {‘1’, ‘2’, ‘a’, ‘b’, ‘c’, ‘1’, ‘n’, ‘c’, ‘1’, ‘2’}
Output: 0 9

Approach: We have to consider the fact that all digits can be treated identically (which means 0 and 5 can be treated as identical but 0 and ‘a’ can’t be treated identical) and also all letters can be treated identically in a similar way. So we iterate through the array and replace every letter with ‘0’ and every number with ‘1’.
This problem then reduces to https://www.geeksforgeeks.org/largest-subarray-with-equal-number-of-0s-and-1s/ .
After modifying the code for the above algorithm to comply with this problem, we come up with the following code to solve the problem.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the starting and the
// ending index of the sub-array with equal
// number of alphabets and numeric digits
void findSubArray(int arr[], int n)
{
    int sum = 0;
    int maxsize = -1, startindex;
    for (int i = 0; i < n; i++) {
  
        // If its an alphabet
        if (isalpha(arr[i])) {
            arr[i] = 0;
        }
  
        // Else its a number
        else {
            arr[i] = 1;
        }
    }
  
    // Pick a starting point as i
    for (int i = 0; i < n - 1; i++) {
        sum = (arr[i] == 0) ? -1 : 1;
  
        // Consider all sub-arrays starting from i
        for (int j = i + 1; j < n; j++) {
            (arr[j] == 0) ? (sum += -1) : (sum += 1);
  
            // If this is a 0 sum sub-array then
            // compare it with maximum size sub-array
            // calculated so far
            if (sum == 0 && maxsize < j - i + 1) {
                maxsize = j - i + 1;
                startindex = i;
            }
        }
    }
  
    // If no valid sub-array found
    if (maxsize == -1)
        cout << maxsize;
    else
        cout << startindex << " " << (startindex + maxsize - 1);
}
  
// Driver code
int main()
{
    int arr[] = { 'A', 'B', 'X', 4, 6, 'X', 'a' };
    int size = sizeof(arr) / sizeof(arr[0]);
  
    findSubArray(arr, size);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach 
class GFG 
{
      
    static boolean isalpha(int input_char)
    {
        if ((input_char >= 65 && input_char <= 90
            || (input_char >= 97 && input_char <= 122)) 
            return true;
              
        return false;
    }
      
    // Function to find the starting and the 
    // ending index of the sub-array with equal 
    // number of alphabets and numeric digits 
    static void findSubArray(int arr[], int n) 
    
        int sum = 0
        int maxsize = -1, startindex = 0
        for (int i = 0; i < n; i++) 
        
      
            // If its an alphabet 
            if (isalpha(arr[i]))
            
                arr[i] = 0
            
      
            // Else its a number 
            else 
            
                arr[i] = 1
            
        
      
        // Pick a starting point as i 
        for (int i = 0; i < n - 1; i++) 
        
            sum = (arr[i] == 0) ? -1 : 1
      
            // Consider all sub-arrays starting from i 
            for (int j = i + 1; j < n; j++)
            
                if(arr[j] == 0
                    sum += -1
                else
                    sum += 1
      
                // If this is a 0 sum sub-array then 
                // compare it with maximum size sub-array 
                // calculated so far 
                if (sum == 0 && maxsize < j - i + 1
                
                    maxsize = j - i + 1
                    startindex = i; 
                
            
        
      
        // If no valid sub-array found 
        if (maxsize == -1
            System.out.println(maxsize); 
        else
            System.out.println(startindex + " " + (startindex + maxsize - 1)); 
    
      
    // Driver code 
    public static void main (String[] args)
    {
          
        int arr[] = { 'A', 'B', 'X', 4, 6, 'X', 'a' }; 
        int size = arr.length; 
      
        findSubArray(arr, size); 
    }
}
  
// This code is contributed by AnkitRai01

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach
  
# Function to find the starting and the
# ending index of the sub-array with equal
# number of alphabets and numeric digits
def findSubArray(arr, n):
    sum = 0
    maxsize = -1
    startindex=0
    for i in range(n):
  
        # If its an alphabet
        if (arr[i].isalpha()):
            arr[i] = 0
          
  
        # Else its a number
        else :
            arr[i] = 1
          
    # Pick a starting poas i
    for i in range(n-1):
        if arr[i]=='1':
            sum=1
        else:
            sum=-1    
  
        # Consider all sub-arrays starting from i
        for j in range(i+1,n):
            if arr[j]==0:
                sum-=1
            else:
                sum+=1    
  
            # If this is a 0 sum sub-array then
            # compare it with maximum size sub-array
            # calculated so far
            if (sum == 0 and maxsize < j - i + 1) :
                maxsize = j - i + 1
                startindex = i
              
          
    # If no valid sub-array found
    if (maxsize == -1):
        print(maxsize,end=" ")
    else:
        print(startindex,(startindex + maxsize - 1))
  
  
# Driver code
arr=['A', 'B', 'X', '4', '6', 'X', 'a'
size =len(arr)
  
findSubArray(arr, size)
  
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach 
using System;
class GFG 
{
      
    static bool isalpha(int input_char)
    {
        if ((input_char >= 65 && input_char <= 90) 
            || (input_char >= 97 && input_char <= 122)) 
            return true;
              
        return false;
    }
      
    // Function to find the starting and the 
    // ending index of the sub-array with equal 
    // number of alphabets and numeric digits 
    static void findSubArray(int []arr, int n) 
    
        int sum = 0; 
        int maxsize = -1, startindex = 0; 
        for (int i = 0; i < n; i++) 
        
      
            // If its an alphabet 
            if (isalpha(arr[i]))
            
                arr[i] = 0; 
            
      
            // Else its a number 
            else
            
                arr[i] = 1; 
            
        
      
        // Pick a starting point as i 
        for (int i = 0; i < n - 1; i++) 
        
            sum = (arr[i] == 0) ? -1 : 1; 
      
            // Consider all sub-arrays starting from i 
            for (int j = i + 1; j < n; j++)
            
                if(arr[j] == 0) 
                    sum += -1; 
                else
                    sum += 1; 
      
                // If this is a 0 sum sub-array then 
                // compare it with maximum size sub-array 
                // calculated so far 
                if (sum == 0 && maxsize < j - i + 1) 
                
                    maxsize = j - i + 1; 
                    startindex = i; 
                
            
        
      
        // If no valid sub-array found 
        if (maxsize == -1) 
            Console.WriteLine(maxsize); 
        else
        Console.WriteLine(startindex + " " + (startindex + maxsize - 1)); 
    
      
    // Driver code 
    public static void Main()
    {
          
        int []arr = { 'A', 'B', 'X', 4, 6, 'X', 'a' }; 
        int size = arr.Length; 
      
        findSubArray(arr, size); 
    }
}
  
// This code is contributed by anuj_67..

chevron_right


Output:

1 4


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.





Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.