Apple telephonic reject
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2021-02-17Added By Anonymous
Source: Link
Location: Bay area
Experience: 6 years
Webex Interview
Very simple question. Find x in an array which is first increasing and then decreasing. Assume there are no duplicates.
I couldn't solve the edge cases in findPivot function in time so reject is a self-prophecy. However, later I came up with this approach. This question is a little different from finding x in a pivoted array because in the latter version you know the subarray you are going to use to search for x. Also, in this case a common binary search function won't work as one of the pivoted array will be in increasing order and the other one will be in the decreasing order.
1__author__ = 'deepika'
2
3
4class Solution:
5
6
7 def findPivot(self, arr, left, right, n):
8
9 while left <= right:
10
11 if left == right:
12 return left
13
14 mid = right - (right - left)/2
15
16 if mid - 1 >= 0 and mid + 1 < n and arr[mid - 1 ] < arr[mid] > arr[mid + 1]:
17 return mid
18
19 if (mid - 1 >= 0 and mid + 1 < n and arr[mid] > arr[mid + 1] and arr[mid] < arr[mid - 1]):
20 right = mid - 1
21 else:
22 left = mid + 1
23 return n-1 #Strictly increasing array
24
25
26 def binarySearch(self, arr, left, right, element, greaterThanFunction):
27
28 while left <= right:
29 mid = right - (right - left)/2
30
31 if arr[mid] == element:
32 return mid
33 if greaterThanFunction(arr[mid], element):
34 right = mid - 1
35 else:
36 left = mid + 1
37 return -1
38
39
40 def findElement(self, arr, x):
41
42 pivot = self.findPivot(arr, 0, len(arr)-1 , len(arr))
43
44 index = self.binarySearch(arr, 0, pivot, x, lambda x, y : x > y )
45 if index == -1:
46 index = self.binarySearch(arr, pivot+1, len(arr) - 1, x, lambda x, y : y > x )
47 print("Found x: ", x, " at pivot: ", pivot)
48 return index
49
50
51s=Solution()
52s.findElement([1, 2, 3, 4, 5], 5)
53s.findElement([4, 5, 3, 2, 1], 5)
54s.findElement([5, 4, 3, 2, 1], 2)
55s.findElement([-10, -9, -8, -7, -6, -5, 0, 7, 5, 4, 3, 2], -10)
56s.findElement([-10, -9, -8, -7, -6, -5, 0, 7, 5, 4, 3, 2], -8)
57s.findElement([-10, -9, -8, -7, -6, -5, 0, 7, 5, 4, 3, 2], 2)
58s.findElement([-10, -8, 0, 7, 5, 4, 3, 2], -10)
59s.findElement([-10, -8, 0, 7, 5, 4, 3, 2], -8)
60s.findElement([-10, -8, 0, 7, 5, 4, 3, 2], 2)