HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Find max element in increasing-decreasing array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
decreasingarraymaxincreasingelementfind

Problem

Question: Find the largest in a list that list is stored as two sections, one in ascending order and the other in descending order. Elements are distinct.

E.g: Input [2 3 4 5 6 7 10 9 8 7]

Output: 10

My solution is below. Works on my unit-tests. Want to know if there any improvements from the coding point of view (esp if it is asked in an interview).

long getMaxIndex(long *arr, size_t size)
{
    long left = 0;
    long right = size - 1;

    if (arr == nil) return 0;

    while (left  arr[mid-1] && arr[mid] > arr[mid+1])
        {
            return mid;
        }

        if (arr[mid] > arr[mid-1])
        {
            left = mid;
        }
        else
        {
            right = mid-1;
        }

        if (arr[mid] > arr[mid+1])
        {
            right = mid;
        }
        else
        {
            left = mid+1;
        }
    }

    return left;
}

Solution

Your code will segfault for array size = 2. Rest looks correct to me.

Specifically, for size = 2,

left = 0
right = 1
mid = 0


And hence, this line:

if (arr[mid] > arr[mid-1] && arr[mid] > arr[mid+1])


will try to access arr[mid-1] which is arr[-1] and can segfault/return incorrect answer.

Code Snippets

left = 0
right = 1
mid = 0
if (arr[mid] > arr[mid-1] && arr[mid] > arr[mid+1])

Context

StackExchange Code Review Q#143057, answer score: 2

Revisions (0)

No revisions yet.