Interview: Find Kth Largest in two arrays of ordered integers

This one is actually an improvement over the usual proforma CS-101 questions. A possible solution is below

One of the key item is whether the answerer address boundary conditions (which is half the solution!)

 

public int FindKthLargest(int[] list1, int[] list2, int kth)
        {
            if ((list1 == null && list2.Length < kth) ||
                (list2 == null && list1.Length < kth) ||
                (list1 != null && list2 != null && (list1.Length + list2.Length) < kth))
            {
                throw new ArgumentException("Lists are too short");
            }
            if (list1 == null)
            {
                return list2[list2.Length - kth];
            }
            if (list2 == null)
            {
                return list1[list1.Length - kth];
            }

            int pt1 = list1.Length - 1;
            int pt2 = list2.Length - 1;
            int maxValue = (list1[pt1] > list2[pt2]) ? list1[pt1--]: list2[pt2--];
            kth--;      
            while (kth > 0)
            {
                maxValue = (list1[pt1] > list2[pt2]) ? list1[pt1--] : list2[pt2--];
                kth--;                    
            }
            return maxValue;
        }

Comments

Popular posts from this blog

Yet once more into the breech (of altered programming logic)

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

How to convert SVG data to a Png Image file Using InkScape