Smallest subarray having an element with frequency greater than that of other elements
Last Updated :
01 Feb, 2023
Given an array arr of positive integers, the task is to find the smallest length subarray of length more than 1 having an element occurring more times than any other element.
Examples:
Input: arr[] = {2, 3, 2, 4, 5}
Output: 2 3 2
Explanation: The subarray {2, 3, 2} has an element 2 which occurs more number of times any other element in the subarray.
Input: arr[] = {2, 3, 4, 5, 2, 6, 7, 6}
Output: 6 7 6
Explanation: The subarrays {2, 3, 4, 5, 2} and {6, 7, 6} contain an element that occurs more number of times than any other element in them. But the subarray {6, 7, 6} is of minimum length.
Naive Approach: A naive approach to solve the problem can be to find all the subarrays which have an element that meets the given condition and then find the minimum of all those subarrays.
- Initialize a variable result to the maximum possible value of an integer and a hash map unmap to store element frequencies. Initialize two variables maxFreq and secondMaxx to store the maximum and second maximum frequencies seen so far in the current subarray.
- Iterate through the input array arr[] with an outer loop variable i.
- For each value of i, iterate through the array again with an inner loop variable j such that j starts at i and goes up to the end of the array.
- For each value of j, increment the frequency of arr[j] in the hash map unmap.
- If the frequency of arr[j] in unmap is greater than the current value of maxFreq, update secondMaxx with the current value of maxFreq and maxFreq with the frequency of arr[j] in unmap.
- If the current subarray (from i to j) has at least two elements and both maxFreq and secondMaxx are greater than 0, update result with the minimum of its current value and the length of the current subarray.
- After the outer loop finishes, print the final value of result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find subarray
void FindSubarray(int arr[], int n)
{
// initialize result as the maximum possible value
int result = INT_MAX;
// iterate through all subarrays starting from index i
for (int i = 0; i < n; i++) {
// unordered_map to store element frequencies
unordered_map<int, int> unmap;
// variables to store maximum and second
// maximum frequency elements
int secondMaxx = -1;
int maxFreq = -1;
// iterate through all subarrays ending at index j
for (int j = i; j < n; j++) {
// increment the frequency of element arr[j] in
// the unordered_map
unmap[arr[j]]++;
// if the frequency of arr[j] is greater than
// maxFreq, update secondMaxx and maxFreq
if (unmap[arr[j]] > maxFreq) {
secondMaxx = maxFreq;
maxFreq = unmap[arr[j]];
}
// if the frequency of arr[j] is less than
// maxFreq but greater than secondMaxx, update
// secondMaxx
else if (unmap[arr[j]] > secondMaxx) {
secondMaxx = unmap[arr[j]];
}
// if the subarray has more than one element and
// both maxFreq and secondMaxx are greater than
// 0, update the result with the length of the
// current subarray
if (j - i + 1 > 1 && maxFreq > 0
&& secondMaxx > 0) {
result = min(j - i + 1, result);
}
}
}
// print the smallest subarray length
cout << result;
}
// Driver Code
int main()
{
int arr[] = { 2, 3, 4, 5, 2, 6, 7, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
FindSubarray(arr, n);
return 0;
}
Java
import java.util.HashMap;
public class Gfg {
public static void FindSubarray(int[] arr, int n) {
// initialize result as the maximum possible value
int result = Integer.MAX_VALUE;
// iterate through all subarrays starting from index i
for (int i = 0; i < n; i++) {
// HashMap to store element frequencies
HashMap<Integer, Integer> hmap = new HashMap<>();
// variables to store maximum and second
// maximum frequency elements
int secondMaxx = -1;
int maxFreq = -1;
// iterate through all subarrays ending at index j
for (int j = i; j < n; j++) {
// increment the frequency of element arr[j] in
// the HashMap
if(hmap.containsKey(arr[j])) {
hmap.put(arr[j], hmap.get(arr[j]) + 1);
} else {
hmap.put(arr[j], 1);
}
// if the frequency of arr[j] is greater than
// maxFreq, update secondMaxx and maxFreq
if (hmap.get(arr[j]) > maxFreq) {
secondMaxx = maxFreq;
maxFreq = hmap.get(arr[j]);
}
// if the frequency of arr[j] is less than
// maxFreq but greater than secondMaxx, update
// secondMaxx
else if (hmap.get(arr[j]) > secondMaxx) {
secondMaxx = hmap.get(arr[j]);
}
// if the subarray has more than one element and
// both maxFreq and secondMaxx are greater than
// 0, update the result with the length of the
// current subarray
if (j - i + 1 > 1 && maxFreq > 0
&& secondMaxx > 0) {
result = Math.min(j - i + 1, result);
}
}
}
// print the smallest subarray length
System.out.println(result);
}
public static void main(String[] args) {
int[] arr = { 2, 3, 4, 5, 2, 6, 7, 6 };
int n = arr.length;
FindSubarray(arr, n);
}
}
Python3
# Function to find subarray
def FindSubarray(arr, n):
# initialize result as the maximum possible value
result = float('inf')
# iterate through all subarrays starting from index i
for i in range(n):
# dictionary to store element frequencies
unmap = {}
# variables to store maximum and second
# maximum frequency elements
secondMaxx = -1
maxFreq = -1
# iterate through all subarrays ending at index j
for j in range(i, n):
# increment the frequency of element arr[j] in
# the dictionary
if arr[j] in unmap:
unmap[arr[j]] += 1
else:
unmap[arr[j]] = 1
# if the frequency of arr[j] is greater than
# maxFreq, update secondMaxx and maxFreq
if unmap[arr[j]] > maxFreq:
secondMaxx = maxFreq
maxFreq = unmap[arr[j]]
# if the frequency of arr[j] is less than
# maxFreq but greater than secondMaxx, update
# secondMaxx
elif unmap[arr[j]] > secondMaxx:
secondMaxx = unmap[arr[j]]
# if the subarray has more than one element and
# both maxFreq and secondMaxx are greater than
# 0, update the result with the length of the
# current subarray
if j - i + 1 > 1 and maxFreq > 0 and secondMaxx > 0:
result = min(j - i + 1, result)
# print the smallest subarray length
print(result)
# Driver Code
arr = [2, 3, 4, 5, 2, 6, 7, 6]
n = len(arr)
FindSubarray(arr, n)
# This code is contributed by divya_p123.
C#
using System;
using System.Collections.Generic;
class Program {
// Function to find subarray
static void FindSubarray(int[] arr, int n)
{
// initialize result as the maximum possible value
int result = int.MaxValue;
// iterate through all subarrays starting from index
// i
for (int i = 0; i < n; i++) {
// unordered_map to store element frequencies
Dictionary<int, int> unmap
= new Dictionary<int, int>();
// variables to store maximum and second
// maximum frequency elements
int secondMaxx = -1;
int maxFreq = -1;
// iterate through all subarrays ending at index
// j
for (int j = i; j < n; j++) {
// increment the frequency of element arr[j]
// in the unordered_map
if (!unmap.ContainsKey(arr[j])) {
unmap.Add(arr[j], 1);
}
else {
unmap[arr[j]]++;
}
// if the frequency of arr[j] is greater
// than maxFreq, update secondMaxx and
// maxFreq
if (unmap[arr[j]] > maxFreq) {
secondMaxx = maxFreq;
maxFreq = unmap[arr[j]];
}
// if the frequency of arr[j] is less than
// maxFreq but greater than secondMaxx,
// update secondMaxx
else if (unmap[arr[j]] > secondMaxx) {
secondMaxx = unmap[arr[j]];
}
// if the subarray has more than one element
// and both maxFreq and secondMaxx are
// greater than 0, update the result with
// the length of the current subarray
if (j - i + 1 > 1 && maxFreq > 0
&& secondMaxx > 0) {
result = Math.Min(j - i + 1, result);
}
}
}
// print the smallest subarray length
Console.WriteLine(result);
}
// Driver Code
static void Main()
{
int[] arr = { 2, 3, 4, 5, 2, 6, 7, 6 };
int n = arr.Length;
FindSubarray(arr, n);
}
}
JavaScript
// JavaScript code equivalent to the C++ program
// Function to find subarray
const FindSubarray = (arr, n) => {
// initialize result as the maximum possible value
let result = Number.MAX_SAFE_INTEGER;
// iterate through all subarrays starting from index i
for (let i = 0; i < n; i++) {
// Map to store element frequencies
let unmap = new Map();
// variables to store maximum and second
// maximum frequency elements
let secondMaxx = -1;
let maxFreq = -1;
// iterate through all subarrays ending at index j
for (let j = i; j < n; j++) {
// increment the frequency of element arr[j] in
// the Map
unmap.set(arr[j], (unmap.get(arr[j]) || 0) + 1);
// if the frequency of arr[j] is greater than
// maxFreq, update secondMaxx and maxFreq
if (unmap.get(arr[j]) > maxFreq) {
secondMaxx = maxFreq;
maxFreq = unmap.get(arr[j]);
}
// if the frequency of arr[j] is less than
// maxFreq but greater than secondMaxx, update
// secondMaxx
else if (unmap.get(arr[j]) > secondMaxx) {
secondMaxx = unmap.get(arr[j]);
}
// if the subarray has more than one element and
// both maxFreq and secondMaxx are greater than
// 0, update the result with the length of the
// current subarray
if (j - i + 1 > 1 && maxFreq > 0 && secondMaxx > 0) {
result = Math.min(j - i + 1, result);
}
}
}
// print the smallest subarray length
console.log(result);
};
// Driver Code
const arr = [2, 3, 4, 5, 2, 6, 7, 6];
const n = arr.length;
FindSubarray(arr, n);
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The problem can be reduced to find out that if there is any element occurring twice in a subarray, then it can be a potential answer. Because the minimum length of such subarray can be the minimum distance between two same elements
The idea is to use an extra array that maintains the last occurrence of the elements in the given array. Then find the distance between the last occurrence of an element and current position and find the minimum of all such lengths.
Below is the implementation of the above approach.
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find subarray
void FindSubarray(int arr[], int n)
{
// If the array has only one element,
// then there is no answer.
if (n == 1) {
cout << "No such subarray!"
<< endl;
}
// Array to store the last occurrences
// of the elements of the array.
int vis[n + 1];
memset(vis, -1, sizeof(vis));
vis[arr[0]] = 0;
// To maintain the length
int len = INT_MAX, flag = 0;
// Variables to store
// start and end indices
int start, end;
for (int i = 1; i < n; i++) {
int t = arr[i];
// Check if element is occurring
// for the second time in the array
if (vis[t] != -1) {
// Find distance between last
// and current index
// of the element.
int distance = i - vis[t] + 1;
// If the current distance
// is less than len
// update len and
// set 'start' and 'end'
if (distance < len) {
len = distance;
start = vis[t];
end = i;
}
flag = 1;
}
// Set the last occurrence
// of current element to be 'i'.
vis[t] = i;
}
// If flag is equal to 0,
// it means there is no answer.
if (flag == 0)
cout << "No such subarray!"
<< endl;
else {
for (int i = start; i <= end; i++)
cout << arr[i] << " ";
}
}
// Driver Code
int main()
{
int arr[] = { 2, 3, 2, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
FindSubarray(arr, n);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to find subarray
public static void FindSubarray(int[] arr,
int n)
{
// If the array has only one element,
// then there is no answer.
if (n == 1)
{
System.out.println("No such subarray!");
}
// Array to store the last occurrences
// of the elements of the array.
int[] vis = new int[n + 1];
Arrays.fill(vis, -1);
vis[arr[0]] = 0;
// To maintain the length
int len = Integer.MAX_VALUE, flag = 0;
// Variables to store
// start and end indices
int start = 0, end = 0;
for(int i = 1; i < n; i++)
{
int t = arr[i];
// Check if element is occurring
// for the second time in the array
if (vis[t] != -1)
{
// Find distance between last
// and current index
// of the element.
int distance = i - vis[t] + 1;
// If the current distance
// is less than len
// update len and
// set 'start' and 'end'
if (distance < len)
{
len = distance;
start = vis[t];
end = i;
}
flag = 1;
}
// Set the last occurrence
// of current element to be 'i'.
vis[t] = i;
}
// If flag is equal to 0,
// it means there is no answer.
if (flag == 0)
System.out.println("No such subarray!");
else
{
for(int i = start; i <= end; i++)
System.out.print(arr[i] + " ");
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 2, 3, 2, 4, 5 };
int n = arr.length;
FindSubarray(arr, n);
}
}
// This code is contributed by divyeshrabadiya07
Python3
# Python3 program for the above approach
import sys
# Function to find subarray
def FindSubarray(arr, n):
# If the array has only one element,
# then there is no answer.
if (n == 1):
print("No such subarray!")
# Array to store the last occurrences
# of the elements of the array.
vis = [-1] * (n + 1)
vis[arr[0]] = 0
# To maintain the length
length = sys.maxsize
flag = 0
for i in range(1, n):
t = arr[i]
# Check if element is occurring
# for the second time in the array
if (vis[t] != -1):
# Find distance between last
# and current index
# of the element.
distance = i - vis[t] + 1
# If the current distance
# is less than len
# update len and
# set 'start' and 'end'
if (distance < length):
length = distance
start = vis[t]
end = i
flag = 1
# Set the last occurrence
# of current element to be 'i'.
vis[t] = i
# If flag is equal to 0,
# it means there is no answer.
if (flag == 0):
print("No such subarray!")
else:
for i in range(start, end + 1):
print(arr[i], end = " ")
# Driver Code
if __name__ == "__main__":
arr = [ 2, 3, 2, 4, 5 ]
n = len(arr)
FindSubarray(arr, n)
# This code is contributed by chitranayal
C#
// C# program for the above approach
using System;
class GFG{
// Function to find subarray
public static void FindSubarray(int[] arr,
int n)
{
// If the array has only one element,
// then there is no answer.
if (n == 1)
{
Console.WriteLine("No such subarray!");
}
// Array to store the last occurrences
// of the elements of the array.
int[] vis = new int[n + 1];
for(int i = 0; i < n + 1; i++)
vis[i] = -1;
vis[arr[0]] = 0;
// To maintain the length
int len = int.MaxValue, flag = 0;
// Variables to store
// start and end indices
int start = 0, end = 0;
for(int i = 1; i < n; i++)
{
int t = arr[i];
// Check if element is occurring
// for the second time in the array
if (vis[t] != -1)
{
// Find distance between last
// and current index
// of the element.
int distance = i - vis[t] + 1;
// If the current distance
// is less than len
// update len and
// set 'start' and 'end'
if (distance < len)
{
len = distance;
start = vis[t];
end = i;
}
flag = 1;
}
// Set the last occurrence
// of current element to be 'i'.
vis[t] = i;
}
// If flag is equal to 0,
// it means there is no answer.
if (flag == 0)
Console.WriteLine("No such subarray!");
else
{
for(int i = start; i <= end; i++)
Console.Write(arr[i] + " ");
}
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 2, 3, 2, 4, 5 };
int n = arr.Length;
FindSubarray(arr, n);
}
}
// This code is contributed by sapnasingh4991
JavaScript
<script>
// Javascript program for the above approach
// Function to find subarray
function FindSubarray(arr, n)
{
// If the array has only one element,
// then there is no answer.
if (n == 1)
{
document.write("No such subarray!");
}
// Array to store the last occurrences
// of the elements of the array.
let vis = new Array(n + 1);
for(let i = 0; i < (n + 1); i++)
vis[i] = -1;
vis[arr[0]] = 0;
// To maintain the length
let len = Number.MAX_VALUE, flag = 0;
// Variables to store
// start and end indices
let start = 0, end = 0;
for(let i = 1; i < n; i++)
{
let t = arr[i];
// Check if element is occurring
// for the second time in the array
if (vis[t] != -1)
{
// Find distance between last
// and current index
// of the element.
let distance = i - vis[t] + 1;
// If the current distance
// is less than len
// update len and
// set 'start' and 'end'
if (distance < len)
{
len = distance;
start = vis[t];
end = i;
}
flag = 1;
}
// Set the last occurrence
// of current element to be 'i'.
vis[t] = i;
}
// If flag is equal to 0,
// it means there is no answer.
if (flag == 0)
document.write("No such subarray!");
else
{
for(let i = start; i <= end; i++)
document.write(arr[i] + " ");
}
}
// Driver code
let arr = [ 2, 3, 2, 4, 5 ];
let n = arr.length;
FindSubarray(arr, n);
// This code is contributed by avanitrachhadiya2155
</script>
Time Complexity: O(N), where n is the length of the array.
Auxiliary Space: O(N).
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