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.

Be the first one to answer
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

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