Maximum length of the sub-array whose first and last elements are same
Last Updated :
08 Feb, 2025
Given a character array arr[] containing only lowercase English alphabets, the task is to print the maximum length of the subarray such that the first and the last element of the sub-array are same.
Examples:
Input: arr[] = {'g', 'e', 'e', 'k', 's'}
Output: 2
Explanation: {'e', 'e'} is the maximum length sub-array satisfying the given condition.
Input: arr[] = {'a', 'b', 'c', 'd', 'a'}
Output: 5
Explanation: {'a', 'b', 'c', 'd', 'a'} is the required sub-array .
[Naive Approach] Using two nested loops
The idea is to use two nested loops where the outer loop selects each character as a potential start of a subarray, and for each start position, the inner loop searches from the end to find the rightmost occurrence of the same character, keeping track of the maximum length of such subarrays found so far.
C++
// C++ program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
#include<iostream>
#include<vector>
using namespace std;
int maxLenSubArray(vector<char> &arr) {
int n = arr.size();
int res = 0;
// Find the maximum length of
// each subarray.
for (int i=0; i<n; i++) {
int j;
// Find the furthest index j
// such that arr[i]==arr[j].
for (j=n-1; j>=i; j--) {
if (arr[i]==arr[j]) break;
}
// Compare size of current subarray.
res = max(res, j-i+1);
}
return res;
}
int main() {
vector<char> arr = {'g', 'e', 'e', 'k', 's'};
cout << maxLenSubArray(arr);
return 0;
}
Java
// Java program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
import java.util.*;
class GfG {
// Function to find the maximum length
// of the subarray such that the first
// and the last element of the sub-array are same.
static int maxLenSubArray(char[] arr) {
int n = arr.length;
int res = 0;
// Find the maximum length of
// each subarray.
for (int i = 0; i < n; i++) {
int j;
// Find the furthest index j
// such that arr[i] == arr[j].
for (j = n - 1; j >= i; j--) {
if (arr[i] == arr[j]) break;
}
// Compare size of current subarray.
res = Math.max(res, j - i + 1);
}
return res;
}
public static void main(String[] args) {
char[] arr = {'g', 'e', 'e', 'k', 's'};
System.out.println(maxLenSubArray(arr));
}
}
Python
# Python program to find the maximum length
# of the subarray such that the first and
# the last element of the sub-array are same.
# Function to find the maximum length
# of the subarray such that the first
# and the last element of the sub-array are same.
def maxLenSubArray(arr):
n = len(arr)
res = 0
# Find the maximum length of
# each subarray.
for i in range(n):
j = n - 1
# Find the furthest index j
# such that arr[i] == arr[j].
while j >= i:
if arr[i] == arr[j]:
break
j -= 1
# Compare size of current subarray.
res = max(res, j - i + 1)
return res
if __name__ == "__main__":
arr = ['g', 'e', 'e', 'k', 's']
print(maxLenSubArray(arr))
C#
// C# program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
using System;
class GfG {
// Function to find the maximum length
// of the subarray such that the first
// and the last element of the sub-array are same.
static int maxLenSubArray(char[] arr) {
int n = arr.Length;
int res = 0;
// Find the maximum length of
// each subarray.
for (int i = 0; i < n; i++) {
int j;
// Find the furthest index j
// such that arr[i] == arr[j].
for (j = n - 1; j >= i; j--) {
if (arr[i] == arr[j]) break;
}
// Compare size of current subarray.
res = Math.Max(res, j - i + 1);
}
return res;
}
static void Main(string[] args) {
char[] arr = { 'g', 'e', 'e', 'k', 's' };
Console.WriteLine(maxLenSubArray(arr));
}
}
JavaScript
// JavaScript program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
// Function to find the maximum length
// of the subarray such that the first
// and the last element of the sub-array are same.
function maxLenSubArray(arr) {
let n = arr.length;
let res = 0;
// Find the maximum length of
// each subarray.
for (let i = 0; i < n; i++) {
let j;
// Find the furthest index j
// such that arr[i] == arr[j].
for (j = n - 1; j >= i; j--) {
if (arr[i] === arr[j]) break;
}
// Compare size of current subarray.
res = Math.max(res, j - i + 1);
}
return res;
}
const arr = ['g', 'e', 'e', 'k', 's'];
console.log(maxLenSubArray(arr));
Time Complexity: O(n^2), as two loops are used.
Auxiliary Space: O(1)
[Efficient Approach] Using Array
The idea is to store the first and last occurrences of each character in separate arrays, and then find the maximum length subarray by calculating the difference between last and first occurrence for each existing character.
Step by step implementation:
- Initialise two arrays of size 26 (for lowercase letters) to store first and last occurrences, with initial values as -1.
- Traverse input array once - for each character, update its first occurrence (if not already set) and last occurrence.
- Find maximum length by checking difference between last and first occurrence for each character that exists in array (first occurrence != -1)
C++
// C++ program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
#include<iostream>
#include<vector>
using namespace std;
int maxLenSubArray(vector<char> &arr) {
int n = arr.size();
// Store first and last occurrence of each character
vector<int> first(26, -1);
vector<int> last(26, -1);
// Find first and last occurrence for each character
for(int i = 0; i < n; i++) {
int idx = arr[i] - 'a';
// If first occurrence
if(first[idx] == -1) {
first[idx] = i;
}
// Update last occurrence
last[idx] = i;
}
// Find max length by checking all characters
int maxLen = 0;
for(int i = 0; i < 26; i++) {
// Only consider if character exists in array
if(first[i] != -1) {
maxLen = max(maxLen, last[i] - first[i] + 1);
}
}
return maxLen;
}
int main() {
vector<char> arr = {'g', 'e', 'e', 'k', 's'};
cout << maxLenSubArray(arr);
return 0;
}
Java
// Java program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
import java.util.*;
class GfG {
static int maxLenSubArray(char[] arr) {
int n = arr.length;
// Store first and last occurrence of each character
int[] first = new int[26];
int[] last = new int[26];
Arrays.fill(first, -1);
Arrays.fill(last, -1);
// Find first and last occurrence for each character
for (int i = 0; i < n; i++) {
int idx = arr[i] - 'a';
// If first occurrence
if (first[idx] == -1) {
first[idx] = i;
}
// Update last occurrence
last[idx] = i;
}
// Find max length by checking all characters
int maxLen = 0;
for (int i = 0; i < 26; i++) {
// Only consider if character exists in array
if (first[i] != -1) {
maxLen = Math.max(maxLen, last[i] - first[i] + 1);
}
}
return maxLen;
}
public static void main(String[] args) {
char[] arr = {'g', 'e', 'e', 'k', 's'};
System.out.println(maxLenSubArray(arr));
}
}
Python
# Python program to find the maximum length
# of the subarray such that the first and
# the last element of the sub-array are same.
def maxLenSubArray(arr):
n = len(arr)
# Store first and last occurrence of each character
first = [-1] * 26
last = [-1] * 26
# Find first and last occurrence for each character
for i in range(n):
idx = ord(arr[i]) - ord('a')
# If first occurrence
if first[idx] == -1:
first[idx] = i
# Update last occurrence
last[idx] = i
# Find max length by checking all characters
maxLen = 0
for i in range(26):
# Only consider if character exists in array
if first[i] != -1:
maxLen = max(maxLen, last[i] - first[i] + 1)
return maxLen
if __name__ == "__main__":
arr = ['g', 'e', 'e', 'k', 's']
print(maxLenSubArray(arr))
C#
// C# program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
using System;
class GfG {
static int maxLenSubArray(char[] arr) {
int n = arr.Length;
// Store first and last occurrence of each character
int[] first = new int[26];
int[] last = new int[26];
Array.Fill(first, -1);
Array.Fill(last, -1);
// Find first and last occurrence for each character
for (int i = 0; i < n; i++) {
int idx = arr[i] - 'a';
// If first occurrence
if (first[idx] == -1) {
first[idx] = i;
}
// Update last occurrence
last[idx] = i;
}
// Find max length by checking all characters
int maxLen = 0;
for (int i = 0; i < 26; i++) {
// Only consider if character exists in array
if (first[i] != -1) {
maxLen = Math.Max(maxLen, last[i] - first[i] + 1);
}
}
return maxLen;
}
static void Main(string[] args) {
char[] arr = { 'g', 'e', 'e', 'k', 's' };
Console.WriteLine(maxLenSubArray(arr));
}
}
JavaScript
// JavaScript program to find the maximum length
// of the subarray such that the first and
// the last element of the sub-array are same.
function maxLenSubArray(arr) {
let n = arr.length;
// Store first and last occurrence of each character
let first = new Array(26).fill(-1);
let last = new Array(26).fill(-1);
// Find first and last occurrence for each character
for (let i = 0; i < n; i++) {
let idx = arr[i].charCodeAt(0) - 'a'.charCodeAt(0);
// If first occurrence
if (first[idx] === -1) {
first[idx] = i;
}
// Update last occurrence
last[idx] = i;
}
// Find max length by checking all characters
let maxLen = 0;
for (let i = 0; i < 26; i++) {
// Only consider if character exists in array
if (first[i] !== -1) {
maxLen = Math.max(maxLen, last[i] - first[i] + 1);
}
}
return maxLen;
}
const arr = ['g', 'e', 'e', 'k', 's'];
console.log(maxLenSubArray(arr));
Time Complexity: O(n)
Auxiliary Space: O(1)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Similar Reads
Find the maximum elements in the first and the second halves of the Array , Given an array arr[] of N integers. The task is to find the largest elements in the first half and the second half of the array. Note that if the size of the array is odd then the middle element will be included in both halves.Examples: Input: arr[] = {1, 12, 14, 5} Output: 12, 14 First half is {1
6 min read
Maximum length of subarray such that all elements are equal in the subarray Given an array arr[] of N integers, the task is to find the maximum length subarray that contains similar elements. Examples: Input: arr[] = {1, 2, 3, 4, 5, 5, 5, 5, 5, 2, 2, 1, 1} Output: 5 Explanation: The subarray {5, 5, 5, 5, 5} has maximum length 5 with identical elements. Input: arr[] = {1, 2,
5 min read
Maximum subarray sum with same first and last element formed by removing elements Given an array arr[] of N integers, the task is to find the maximum sum of subarray having length an at least 2 whose first and last elements are the same after removing any number of array elements. If there exists no such array, then print 0. Examples: Input: arr[] = {-1, -3, -2, 4, -1, 3}Output:
6 min read
Maximum in array which is at-least twice of other elements Given an array of integers of length n. Our task is to return the index of the max element if the it is at least twice as much as every other number in the array. If the max element does not satisfy the condition return -1. Examples: Input : arr = {3, 6, 1, 0} Output : 1 Here, 6 is the largest integ
7 min read
Maximum length sub-array which satisfies the given conditions Given a binary array arr[], the task is to find the length of the longest sub-array of the given array such that if the sub-array is divided into two equal-sized sub-arrays then both the sub-arrays either contain all 0s or all 1s. For example, the two sub-arrays must be of the form {0, 0, 0, 0} and
12 min read