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)
{
SortedSet<int> set = new SortedSet<int>(Comparer<int>.Create((a, b) =>
{
if (b == a)
{
return 1; // This works to add duplicate but breaks remove and elementAt methods
}
else
{
return b-a;
}
}));
for (int i = 0; i < arr.Length; i++)
{
set.Add(arr[i]);
}
//int ans = 0;
for (int i = 0; i < n - 1; i++)
{
set.Remove(set.Min);
}
return set.Min;
}
Follow up: Can we have better solution with less complexity? Ans : QuickSelect
https://leetcode.com/problems/maximum-subarray/
public int MaxSubArray(int[] nums) {
if(nums.Length == 1)
{
return nums[0];
}
int sum = 0;
int max = int.MinValue;
for(int i =0;i <nums.Length; i++)
{
sum = sum + nums[i];
if(sum > max)
{
max = sum;
}
if (sum < 0)
{
sum = 0;
}
}
return max;
}
Follow up question on 2nd: Do you see any problem if all elements are negative. I got confused and started thinking for another approach but after interview I realized my approach was correct for all negative numbers as well.