Smallest Subarray With K Distinct Elements

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.
Input Format :
The first line contains two integers 'N' and 'K' denoting the total number of integers and number of distinct integers respectively. 

The second line contains 'N' space-separated integers describing elements of the array 'A'.
Output Format :
Print two space-separated integers denoting the starting and ending index of the subarray if it exists, otherwise print -1.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Assume array starts with 0 index.
If more than one solution is possible then print the subarray with smaller left index.
Constraints :
1 <= N, K <= 10^6
-10^5 <= A[i] <= 10^5

Time limit: 1 sec
CodingNinjas
author
2y

Approach (Using Sliding Window) :

1) Initialize the map to store the count of each element.

2) Initialize start and end to store the index of the required subarray.

3) i, j denote the start and end of t...read more

CodingNinjas
author
2y
Brute Force Approach

Algorithm

  • Pick each element from the array as the starting element(i) of the subarray,
    • Initialize an empty set to store distinct elements in the subarray.
    • Pick each remaining element...read more
CodingNinjas
author
2y
Sliding Window Approach

Using the sliding window technique

Algorithm

  • Initialize the map to store the count of each element.
  • Initialize start and end to store the index of the required subarray.
  • i, j deno...read more
Add answer anonymously...
Ernst & Young Technology Consultant Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter