Friday, August 23, 2019

33. Search in Rotated Sorted Array

Here is the link.

C# Case study: Road to executable code on August 20, 2019

I went to onsite and then I had a coding interview to write code on white board. The stardard is high, one of advice is to write executable code. What I did is to try to write the code using the idea shared my post written on August 22, 2019, here is the link.
I like to share my code written on white board, and then discuss bugs I created, compared to executable code, how many things I can think about working on, make improvements.
My code written has index-out-of-range error since middle - 1 and middle + 1 is out-of-range.
Given the rotated sorted array [3, 1], target is 1, the code will not work at all.
 /// modified binary search 
        public int Search(int[] numbers, int target)
        {
            if (numbers == null || numbers.Length == 0)
                return -1;

            var start = 0;
            var end = numbers.Length - 1;

            while (start <= end)
            {
                var middle = start + (end - start) / 2;
                var middleValue = numbers[middle];

                if (middleValue == target)
                    return middle;
                
                // two range [start, middle - 1], [middle + 1, end]
                // range can be one value only           
                var leftAsc  = numbers[middle - 1] >= numbers[start]; // bug: out-of-range error
                var rightAsc = numbers[end] >= numbers[middle + 1];

                // missing cases
                if (leftAsc && isInRange(target, new int[] { numbers[start], numbers[middle - 1] }))
                {                    
                    end = middle - 1;                    
                }
                else if (rightAsc && isInRange(target, new int[] { numbers[middle + 1], numbers[end] }))
                {
                    start = middle + 1; 
                }
            }

            return -1;
        }

        private static bool isInRange(int target, int[] range)
        {
            return target >= range[0] && target <= range[1];
        }
Follow up on August 23, 2019
Give every idea a chance to live
I spent extra 20 minutes to make the above idea work, still check range [start, middle - 1]. Here is the link.
C# various practices in 2019, here is the link.


No comments:

Post a Comment