leetcode/34_first_last_elem_sorted_array
34_first_last_elem_sorted_array
dz /
leetcode /
34_first_last_elem_sorted_array
Summary
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity.
Node Tree
Nodes
intuition
|
content
|
I've come to recognize this as a prototypical binary search problem. Sorted array, O(log(n)) time. The special extra bit here is making sure the array returns [-1,-1] if a range hasn't been found.
|
children
|
two_pass_binary_search, two_pointers
|
two_pointers
|
content
|
I'm guessing this solution will ultimately use the left/right pointer technique. You can solve this in about linear time by inching both sides until they converge towards the target. Based on what I've seen so far, a log time solution would involve some kind of midpoint?
|
parents
|
intuition
|
find_lower_bound
|
content
|
This is done based on which subarray to choose. To choose the lower bound: make sure the subarray has the range for the target. Eventually the midpoint will be the lower bound. The lower bound will always be greater than or equal to the first value of the left subarray.
|
children
|
find_upper_bound (similar)
|
parents
|
two_pass_binary_search
|
0_brute_force
|
content
|
To begin, a hypothetical discussion of the brute force approach, which is a linear sweep. The first occurance is the lower bound, and the upper bound happens when the value is greater than the target or the end of the array. This approach however doesn't take advantage of the sorted nature of the array.
|
parents
|
editorial
|
find_first_pos
|
content
|
2 situations when an index will be the first occurance of the target in the array. 1. mid is equal to begin, which implies the first element in remaining subarray. 2. The element to the left of the index is not equal to the target being looked for (mid-1). If condition not met, keep searching the left side of array for first occurance of target.
|
children
|
only_when_midpoint_is_target (this only happens when midpoint is found to be target), update_midpoint (when nums[mid]==target), find_last_pos (similar)
|
parents
|
two_binary_searches
|
find_last_pos
|
content
|
inverse of finding first position. 1. mid is same as end (instead of begin), which implies last elem in remaining array. 2. element to right of mid (mid + 1) is not equal to the target, meaning keep searching right.
|
children
|
update_midpoint (when nums[mid]==target)
|
parents
|
find_first_pos
|