Find Low/High Index of a Key in a Sorted Array - Coderust: Hacking the Coding Interview Log InJoin for free Ask a Question Find Low/High Index of a Key in a Sorted ArrayGiven a sorted array of integers, return the low and high index of the given element. Statement#We’re given a sorted array of integers,
Example#In the array below, indices are shown in grey and values are shown in green. Note that the actual input can be very large in size. According to the above example, the
Try it yourself#To test our code, the input array will be:
C++ Java Python JS Ruby Go #include <iostream> #include <vector> using namespace std; int FindLowIndex(vector<int>& nums, int target) { return -2; } int FindHighIndex(vector<int>& nums, int target) { return -2; } # Enter to Rename, Shift+Enter to Preview Test Save Reset Solution#Linearly scanning the sorted array for We need to binary search twice: the first time to find the Low index#Let’s look at the algorithm for finding the
High index#Similarly, we can find the
Let’s find
Created with Fabric.js 3.6.6low012345678910125555555520midhighkey: 5Let's start with finding low index on array 'arr'We will move low and high towards each otheruntil low crosses high. 1 of 12 C++ Java Python JS Ruby Go #include <iostream> #include <vector> using namespace std; // Finding the low index of the target element int FindLowIndex(vector<int>& nums, int target) { int low = 0; int high = nums.size() - 1; int mid = high / 2; while (low <= high) { int mid_elem = nums[mid]; // Target value is less than the middle value if (mid_elem < target) { low = mid + 1; } // Target value is greater than or equal to the middle value else { high = mid - 1; } // Updating the mid value mid = low + (high - low) / 2; } if (low < nums.size() && nums[low] == target) { return low; } # Enter to Rename, Shift+Enter to Preview Run Save Reset Time complexity#Since we are using binary search, the time complexity is logarithmic, O(logn)O(logn)O(logn). Even though we do the binary search twice, the asymptotic time complexity is still O(logn)O(logn)O(logn). Space complexity#The space complexity is constant, O(1)O(1)O(1), since no extra storage is used. Back Rotate an Array by N Elements Next Move All Zeros to the Beginning of the Array Mark as Completed Report an Issue |