Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Smallest Subarray With K Distinct Elements
EASY
20 mins
73 upvotes
Arrays
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Arrays
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Smallest Subarray With K Distinct Elements

Contributed by
Sakshi Bansal
Easy
yellow-spark
0/40
Avg time to solve 20 mins
Success Rate 80 %
Share
73 upvotes

Problem Statement

Given an array 'A' consisting of 'N' integers, find the smallest subarray of 'A' containing exactly 'K' distinct integers.

Note :
If more than one such contiguous subarrays exist, consider the subarray having the smallest leftmost index.

For example - if A is [1, 2, 2, 3, 1, 3 ] and k = 2 then the subarrays: [1,2], [2,3], [3,1], [1,3] are the smallest subarrays containing 2 distinct elements. In this case, we will consider the starting and ending index of subarray [1,2] i.e. 0 and 1.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1 :
4 3
1 1 2 1 2
Sample Output 1 :
-1
Explanation Of Sample Input 1 :
The value of k = 3 and there are only two distinct elements in the given array i.e 2 and 3. Therefore there exist no subarray with 3 distinct elements.
Sample Input 2 :
8 3
4 2 2 2 3 4 4 3 
Sample Output 2 :
3 5
Reset Code
Full screen
Auto
copy-code
Console