Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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;
}


Java




// 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


Python3




# 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 point as 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


C#




// 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..


Javascript




<script>
    // Javascript implementation of the approach
     
    function isalpha(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
    function findSubArray(arr, n)
    {
        let sum = 0;
        let maxsize = -1, startindex = 0;
        for (let i = 0; i < n; i++)
        {
       
            // If its an alphabet
            if (isalpha(arr[i].charCodeAt()))
            {
                arr[i] = 0;
            }
       
            // Else its a number
            else
            {
                arr[i] = 1;
            }
        }
       
        // Pick a starting point as i
        for (let i = 0; i < n - 1; i++)
        {
            sum = (arr[i] == 0) ? -1 : 1;
       
            // Consider all sub-arrays starting from i
            for (let 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)
            document.write(maxsize + "</br>");
        else
            document.write(startindex + " " + (startindex + maxsize - 1) + "</br>");
    }
     
    let arr = [ 'A', 'B', 'X', '4', '6', 'X', 'a' ];
    let size = arr.length;
 
    findSubArray(arr, size);
 
</script>


Output

1 4

Time Complexity: O(n2), where n is the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.



Last Updated : 07 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads