Linkedin | Phone screen | Senior Software Engineer- Questions+ Need help with ans
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2021-07-14Added By Anonymous
Source: Link
Hi All,
I had a tech phone screen with LinkedIn today. It started with introduction of two interviewers and then I was asked below two questions:
I use C# language.
https://leetcode.com/problems/kth-largest-element-in-an-array/
I tried to implement this with SortedSet which does not allow duplicate elements like Priority Queue of Java. My question is: do we have any hack through which we can add duplicate elements in SortedSet without breaking it's remove and elementAt methods.
public int NthLargestElement(int[] arr, int n)
{
1 SortedSet<int> set = new SortedSet<int>(Comparer<int>.Create((a, b) =>
2 {
3 if (b == a)
4 {
5 return 1; // This works to add duplicate but breaks remove and elementAt methods
6 }
7 else
8 {
9 return b-a;
10 }
11 }));
12
13 for (int i = 0; i < arr.Length; i++)
14 {
15 set.Add(arr[i]);
16 }
17
18 //int ans = 0;
19 for (int i = 0; i < n - 1; i++)
20 {
21 set.Remove(set.Min);
22 }
23
24 return set.Min;
25
26 }
27
28 Follow up: Can we have better solution with less complexity? Ans : QuickSelect
29 https://leetcode.com/problems/maximum-subarray/
public int MaxSubArray(int[] nums) {
if(nums.Length == 1)
{
return nums[0];
}
1 int sum = 0;
2 int max = int.MinValue;
3
4
5 for(int i =0;i <nums.Length; i++)
6 {
7
8 sum = sum + nums[i];
9
10
11 if(sum > max)
12 {
13 max = sum;
14 }
15
16 if (sum < 0)
17 {
18 sum = 0;
19 }
20 }
21
22 return max;
23
24}
25Follow up question on 2nd: Do you see any problem if all elements are negative. I got confused and started thinking for anothe