Smallest Subarray With K Distinct Elements

Given an array A consisting of N integers, your task is to find the smallest subarray of A that contains exactly K distinct integers.

If multiple such subarrays exist, return the one with the smallest leftmost index.

Input:

The input consists of:

The first line contains two integers 'N' and 'K', representing the total number of integers and the number of distinct integers, respectively. The second line contains 'N' space-separated integers, the elements of the array 'A'.

Output:

The output should be:

Two space-separated integers representing the starting and ending indices of the subarray, or -1 if such a subarray does not exist.

Example:

Input:
N = 6, K = 2
A = [1, 2, 2, 3, 1, 3]
Output:
0 1
Explanation:

The smallest subarrays containing 2 distinct elements are [1, 2], [2, 3], [3, 1], and [1, 3]. Among these, the subarray [1, 2] starts at index 0 and ends at index 1, which is the smallest leftmost index.

Constraints:

  • 1 <= N, K <= 106
  • -105 <= A[i] <= 105
  • Time limit: 1 sec

Note:

You do not need to print anything; the function implementation is enough. Assume the array is 0-indexed. In the event of multiple valid solutions, select the subarray with the smallest left index.

AnswerBot
4mo

Find the smallest subarray in an array with exactly K distinct elements.

  • Use a sliding window approach to keep track of the subarray with K distinct elements.

  • Use a hashmap to store the frequency of eac...read more

Help your peers!
Select
Add answer anonymously...

Ernst & Young Technology Consultant interview questions & answers

A Technology Consultant was asked 1mo agoQ. What are your expectations from this role?
A Technology Consultant was asked Q. How do you detect and handle memory leaks in Node.js?
A Technology Consultant was asked Q. What is cloud computing?

Popular interview questions of Technology Consultant

A Technology Consultant was asked 1mo agoQ1. What are your expectations from this role?
A Technology Consultant was asked Q2. How do you detect and handle memory leaks in Node.js?
A Technology Consultant was asked Q3. What is cloud computing?
Ernst & Young Technology Consultant Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits