(This question has been seen in the interviews of the following companies: Google)
Give an array A of n integers where 1 <= a[i] <= K.
Find out the length of the shortest sequence that can be constructed out of numbers 1, 2, .. k that is NOT a subsequence of A.
eg. A = [4, 2, 1, 2, 3, 3, 2, 4, 1], K = 4
All single digits appears.
Each of the 16 double digit sequences, (1,1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2) ... appears.
Because (1, 1, 2) doesn't appear, return 3.
Solution:
The optimal solution is a little tricky. Can you prove it?
public int shortestNonSeq(int[] a, int k) {
int result = 0;
Set flag = new HashSet();
for (int i = 0; i < a.length; i ) {
if (!flag.contains(a[i])) {
flag.add(a[i]);
if (flag.size() == k) {
result ;
flag = new HashSet<>();
}
}
}
return result 1;
}
Get one-to-one training from Google Facebook engineers
Top-notch Professionals
Learn from Facebook and Google senior engineers interviewed 100+ candidates.
Most recent interview questions and system design topics gathered from aonecode alumnus.
One-to-one online classes. Get feedbacks from real interviewers.
Customized Private Class
Already a coding expert? - Advance straight to hard interview topics of your interest.
New to the ground? - Develop basic coding skills with your own designated mentor.
Days before interview? - Focus on most important problems in target company question bank.