Asked inUber,SDE-2

Smallest Subarray with K Distinct Elements Problem

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

Input:

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

Output:

Output two space-separated integers denoting the starting and ending indices of the subarray if it exists; otherwise, print -1.

Example:

Suppose A = [1, 2, 2, 3, 1, 3] and K = 2. The smallest subarrays with 2 distinct elements include [1,2], [2,3], [3,1], and [1,3]. The preferred subarray based on the smallest starting index is [1,2], which starts and ends at indices 0 and 1, respectively.

Constraints:

  • 1 <= N, K <= 10^6
  • -10^5 <= A[i] <= 10^5
  • Time limit: 1 sec

Note:

You do not need to print anything; it has already been taken care of. Just implement the given function. Assume the array starts at index 0. If multiple solutions are possible, select the subarray with the smaller starting index.

Shubham Kumar Gupta
1y
simple make a window and keep on moving starting with i=0, j=0, keep increasing j until it is visited so yes a visited map is requried., and manage MaxAchieved till Now;
Help your peers!
Add answer anonymously...
Uber SDE-2 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