57. Insert Interval

Insert Interval

You are given an array of non-overlapping intervals intervals,

where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti.

You are also given an interval newInterval = [start, end] that represents the start and end of another interval.

Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).

Return intervals after the insertion.

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]

Output:[[1,5],[6,9]]

Insert Interval Java Solution With Linear Search Approach

we will need to insert the newInterval into the original list keeping the start value of intervals in ascending order.

So, the new problem is given N intervals in ascending order of the start and another interval, newInterval, insert the newInterval in the list in the order of its start value.

This can be done using linear search, we can iterate over the intervals in the list, and the newInterval should be inserted just before the interval having a greater start value.

This way, we can produce the list of intervals in ascending order of their start value and solve it using the algorithm

Insert Interval and Merge Overlapping Intervals

    
class Solution {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        intervals = insertIntervalFun(intervals, newInterval);
        
        List answer = new ArrayList<>();
        for(int i = 0; i < intervals.length; i++){
            int[] currentInterval = {intervals[i][0], intervals[i][1]};
            
            //merge 
            //no overlapping found
            while(i < intervals.length && isOverlap(currentInterval, intervals[i])){
                currentInterval = mergeIntervals(currentInterval, intervals[i]);
                i++;
            }
            i--;
            answer.add(currentInterval);
        }
        
        return answer.toArray(new int[answer.size()][2]); 
    }
    
    int[] mergeIntervals(int x[], int[] y){
        int[] interval_new = {Math.min(x[0], y[0]),  Math.max(x[1], y[1])}; 
        return interval_new;
    }
    
    boolean isOverlap(int[] x, int[] y){
        return Math.min(x[1], y[1]) - Math.max(x[0], y[0]) >= 0;
    }
    
    int[][] insertIntervalFun(int[][] intervals, int[] newInterval){
        boolean isInsertedNewInterval = false;        
        List list = new ArrayList<>(Arrays.asList(intervals));
        
        for(int i = 0; i < intervals.length; i++){
            if(newInterval[0] < intervals[i][0]){
                //we have found our position to insert this new interval
                list.add(i, newInterval);
                isInsertedNewInterval = true;
                break;
            }   
        }
        
        if(!isInsertedNewInterval){
            list.add(newInterval);
        }
        
        return list.toArray(new int[list.size()][2]);
    }
}        
    

Explanation

This code inserts a new interval into a list of intervals and merges any overlapping intervals.

Key Methods

  • insert: The main function that handles the interval insertion and merging.
  • mergeIntervals: Merges two overlapping intervals into one.
  • isOverlap: Checks whether two intervals overlap.
  • insertIntervalFun: Finds the correct position to insert the new interval and returns the updated list of intervals.

Algorithm

  1. Call the helper function insertIntervalFun to insert the new interval into its correct position in the list of intervals.

  2. Iterate through the intervals and merge any overlapping intervals:

    • For each interval, initialize it as the currentInterval.

    • If the next interval overlaps with the currentInterval, merge them into one interval using mergeIntervals.

    • Continue merging overlapping intervals until no more overlaps are found.

    • Add the merged interval to the result list.

  3. Convert the result list into a 2D array and return it.

Complexity Analysis

  • Time Complexity: O(n)
    • The insertion operation in insertIntervalFun runs in O(n) as it iterates through the intervals to find the correct position for the new interval.

    • The merging operation iterates through all intervals once, also taking O(n).

  • Space Complexity: O(n)
    • Additional space is used for the result list and the auxiliary data structures during merging.

Approach 2: Binary Search

The only difference with this approach would be that instead of using linear search to find the suitable position of newInterval,

we can use binary search as the list of intervals is sorted in order of their start time.

We need to find the first interval in the list intervals having a start value greater than the start value of newInterval.

Apart from this change, the logic remains the same for this approach;

we insert the interval at its place using binary search and then merge the overlapping intervals using the same algorithm we used previously.

    
class Solution {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        intervals  = insertIntervalfun(intervals, newInterval);
        
        List answer_interval_list = new ArrayList<>();
        for(int i = 0; i < intervals.length; i++){
            int[] currentInterval = {intervals[i][0], intervals[i][1]};
            
            //continue merge
            //no overlappinng
            while(i < intervals.length && isOverlappingInterval(currentInterval, intervals[i])){
                currentInterval = mergeIntervals(currentInterval, intervals[i]);
                i++;
            }
            i--;
            answer_interval_list.add(currentInterval);
        }
        
        return answer_interval_list.toArray(new int[answer_interval_list.size()][2]);
    }
    
    int[] mergeIntervals(int[] x, int[] y){
        int[] newInterval = {Math.min(x[0], y[0]), Math.max(x[1],y[1])};
        return newInterval;
    }
    
    boolean isOverlappingInterval(int[] x, int[] y){
        return Math.min(x[1], y[1]) - Math.max(x[0], y[0]) >= 0;
    }
    
    int[][] insertIntervalfun(int[][] intervals, int[] newInterval){
        List list = new ArrayList<>(Arrays.asList(intervals));
        int index = UpperBoundFun(intervals, newInterval);
        
        if(index != intervals.length){
            list.add(index, newInterval);
        }else{
            list.add(newInterval);
        }
        
        return list.toArray(new int[list.size()][2]);
    }
    
    int UpperBoundFun(int[][] intervals, int[] newInterval){
        if(intervals.length == 0){
            return 0; //if interval is empty then add on 0 index
        }
        
        int start = 0;
        int end = intervals.length - 1;
        int answer = intervals.length;
        
        while(start <= end){
            int mid = (start + end)/2;
            if(intervals[mid][0] > newInterval[0]){
                answer = mid;
                end = mid - 1;
            }
            else{
                start = mid + 1;
            }
        }
        return answer;
    }
}        
    

Explanation

This code inserts a new interval into a list of intervals, maintaining order, and merges any overlapping intervals.

Key Methods

  • insert: The main method that handles insertion and merging of intervals.
  • mergeIntervals: Merges two overlapping intervals into a single interval.
  • isOverlappingInterval: Checks if two intervals overlap.
  • insertIntervalfun: Inserts the new interval into the correct position in the list.
  • UpperBoundFun: Finds the appropriate index for the new interval using binary search.

Algorithm

  1. Call insertIntervalfun to insert the new interval into its correct position using binary search for efficiency.

  2. Iterate through the updated intervals:

    • Initialize currentInterval as the current interval.

    • Merge overlapping intervals using mergeIntervals.

    • Continue merging until no overlaps are found, then add the merged interval to the result list.

  3. Convert the result list to a 2D array and return it.

Complexity Analysis

  • Time Complexity: O(n log n)
    • Binary search in UpperBoundFun runs in O(log n).

    • The merging operation iterates through all intervals in O(n).

  • Space Complexity: O(n)
    • Additional space is used for the result list and auxiliary data structures.

Continue Reading →

Search Insert Position

35. Search Insert Position

Given a sorted array of distinct integers and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [1,3,5,6], target = 5
Output: 2

Example 2:

Input: nums = [1,3,5,6], target = 2
Output: 1

Example 3:

Input: nums = [1,3,5,6], target = 7
Output: 4

Approach 1: Binary Search

๐Ÿ” Intuition

Looking at the nature of the problem, it’s clear that binary search is a perfect fit. Binary search is a powerful algorithm used to find the position of a target value in a sorted array.

The idea is simple: at each step, you compare the middle element of the current range to your target.

  • If the target equals the middle element, you’ve found your answer.
  • If the target is smaller, search the left half.
  • If the target is larger, search the right half.

๐Ÿงญ Step-by-Step

To keep track of where we're searching, we use two pointers: left and right. Initially, left = 0 and right = n - 1.

While left <= right:

  • Find the middle index: pivot = (left + right) / 2
  • If nums[pivot] == target, you’ve found it.
  • If target < nums[pivot], move the search to the left: right = pivot - 1
  • If target > nums[pivot], search the right: left = pivot + 1

If the loop ends without finding the target, it means the value isn’t in the array. At that point, left will point to the correct index to insert the target if needed.

⚠️ Handling Integer Overflow

A common issue in languages like Java or C++ is that (left + right) / 2 can cause overflow when the values are too large (exceeding 231−1).

To avoid this, calculate the pivot like this:

  • pivot = left + (right - left) / 2; (safe and preferred)
  • pivot = (left + right) >> 1; (bitwise method, slightly faster)

๐Ÿงช Algorithm

  1. Initialize: left = 0, right = n - 1
  2. While left <= right:
    • Calculate pivot
    • If nums[pivot] == target: return pivot
    • If target < nums[pivot]: right = pivot - 1
    • Else: left = pivot + 1
  3. Return left as the insertion position if not found

Java code


class Solution {
  public int searchInsert(int[] nums, int target) {
	  int left=0;
	  int right=nums.length-1;
	  int result=0;
	  while(left<=right){
		  int mid=(left+right)/2;
		  int curr=nums[mid];
		  if(curr>target){ 
			  right=mid-1; result=right+1;
		  }
		  else if(curr<target){  
			  left=mid+1; result=left;
		  }
		  else
			  return mid;
	  }
	 return result;
  }
}

๐Ÿ“ˆ Complexity Analysis

Time Complexity: O(logN)
Each time, we divide the problem in half. According to the Master Theorem:

T(N) = aT(N/b) + ฮ˜(Nd)

Here, a = 1 (one subproblem), b = 2 (size halves), and d = 0 (constant time). This leads us to Case 2 of the theorem, giving us: O(logN).

Space Complexity: O(1)
No extra space is used—just a few pointers. Very space-efficient!

Continue Reading →

278. First Bad Version

278. First Bad Version

Imagine you're the product manager in charge of launching a new product. Everything is going great until — boom! — one of the versions fails the quality check.

The problem? Once a version turns out to be bad, every version that comes after it is also bad because each version builds on the one before it.

Now, suppose there are n versions, numbered from 1 to n. Your goal is simple: figure out which version was the first one that went bad.

Luckily, you have access to a helper function called isBadVersion(version). It tells you whether a particular version is bad.

Your task is to use this function smartly to find the first bad version — and do it using as few API calls as possible.

Example 1:

Input: n = 5, bad = 4
Output: 4

Explanation:
isBadVersion(3) → false
isBadVersion(5) → true
isBadVersion(4) → true
So version 4 is the first one that went wrong.

Example 2:

Input: n = 1, bad = 1
Output: 1

278. First Bad Version

Approach #1: Linear Scan (Brute Force)

The simplest way to solve this problem is by checking each version one by one until we find the first one that’s bad. This is called a linear scan or brute-force approach.

Here’s how that would look in Java:


// The isBadVersion API is defined in the parent class VersionControl
// boolean isBadVersion(int version);

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        for (int i = 1; i <= n; i++) {
            if (isBadVersion(i)) {
                return i;
            }
        }
        return n;
    }
}
  

Complexity Analysis

  • Time Complexity: O(n) – In the worst case, we may check all versions from 1 to n.
  • Space Complexity: O(1) – No extra space is used apart from a few variables.

This method is easy to understand but not efficient for large values of n. That’s why it often runs into Time Limit Exceeded errors on platforms like LeetCode.


Approach #2: Binary Search (Efficient & Accepted)

A much faster way to solve the problem is by using binary search. Instead of checking every version, we can eliminate half of the versions in each step.

Let’s understand this with two possible scenarios:

Scenario 1: isBadVersion(mid) returns false

  Versions:   1  2  3  4  5  6  7  8  9
              G  G  G  G  G  G  B  B  B
              |           |           |
            left         mid        right
  

If the middle version is good, we can ignore it and everything before it. So we shift left = mid + 1.

Scenario 2: isBadVersion(mid) returns true

  Versions:   1  2  3  4  5  6  7  8  9
              G  G  G  B  B  B  B  B  B
              |           |           |
            left         mid        right
  

If the middle version is bad, it might be the first bad one — or maybe an earlier version is the culprit. So we shift right = mid.

This way, we slowly narrow down the search space until left == right, which is our answer.

Binary Search Java Implementation


public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int left = 1;
        int right = n;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (isBadVersion(mid)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }
}
  

Complexity Analysis

  • Time Complexity: O(log n) – We cut the search space in half each time.
  • Space Complexity: O(1) – Just two pointers, no extra storage.

Important Notes

  • Use int mid = left + (right - left) / 2 instead of (left + right)/2 to prevent integer overflow.
  • This approach is fast and efficient — and usually the one accepted in coding interviews and competitive platforms.
  • Binary search works best when the data has a sorted or predictable structure, like this one where all versions after the first bad version are also bad.

Fun fact: Even expert programmers have made the mistake of integer overflow in binary search — it went unnoticed in a famous book's implementation for over 20 years!

To find the first bad version quickly, the best approach is to use binary search. Instead of checking every version one by one, we check the middle version and narrow down the range based on the result.

Java Code: First Bad Version

Here’s how you can implement it in Java:



public int firstBadVersion(int n) {
    int left = 1;
    int right = n;

    while (left < right) {
        int mid = left + (right - left) / 2;

        if (isBadVersion(mid)) {
            right = mid; // Look in the left half
        } else {
            left = mid + 1; // Look in the right half
        }
    }

    return left; // First bad version
}
  

This code is using a binary search strategy. It starts with the entire range of versions and keeps splitting it in half.

- If the middle version is bad, we know the first bad version must be at that point or earlier, so we move the right pointer.
- If it’s good, then the first bad one must be after that, so we move the left pointer.

Eventually, both pointers will meet at the exact version where things started going wrong.

Why is the Time Complexity O(log n)?

The reason this algorithm is so efficient is because it cuts the search range in half every time. That’s the power of binary search.

In the worst case, you'll end up making around log₂(n) API calls — way fewer than checking all n versions one by one. That gives us a time complexity of O(log n).

This is much better than a brute-force solution with O(n) time complexity, especially when n is very large. Plus, since we’re only using two variables (left and right), the space complexity is just O(1).

Here’s the Java Code


/* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int start = 1;
        int end = n;
        int result = 1;
        while(start <= end){
            int mid = start + (end-start)/2;
            if(isBadVersion(mid)){
                end = mid - 1;
                result = mid;
            }else
                start = mid + 1;
            }
        return result;
    }
}
Continue Reading →

Binary Search Explained | ExpertFunda

Binary Search Made Simple

What’s Binary Search All About?

Binary search is one of those core ideas in programming that you’ll see everywhere. If you have a sorted list or array, binary search helps you find what you’re looking for quickly by cutting the list in half over and over again.

How Does It Work?

Let’s say you’re looking for a number in a sorted array. Instead of checking every element one by one (like linear search), binary search starts in the middle.

If the middle value is what you need—great, you’re done! If the value is smaller than your target, you throw away the left half. If it’s larger, toss the right half. Rinse and repeat until you find your target or run out of elements.

Thinking About It Step by Step

Here’s how we break it down:

  1. Start with two pointers: left = 0 and right = nums.length - 1.
  2. While left <= right:
    • Find the middle index: mid = left + (right - left) / 2
    • If nums[mid] is your target, return mid
    • If nums[mid] < target, move left to mid + 1
    • If nums[mid] > target, move right to mid - 1
  3. If nothing is found, return -1

Here’s the Java Code


class Solution {
	public int search(int[] nums, int target) {
		// Set the left and right boundaries
		int left = 0, right = nums.length - 1;

		// Under this condition
		while (left <= right) {
			// Get the middle index and the middle value.
			int mid = left + (right - left) / 2;

			// Case 1, return the middle index.
			if (nums[mid] == target) {
				return mid;
			}
			// Case 2, discard the smaller half.
			else if (nums[mid] < target) {
				left = mid + 1;
			}
			// Case 3, discard the larger half.
			else {
				right = mid - 1;
			}
		}

		// If we finish the search without finding target, return -1.
		return -1;
	}
}
  

How Fast Is Binary Search?

Time Complexity: O(log n)

Every time you check the middle, you’re cutting the list in half. So even if the list is huge, it takes only a few steps to find the value—or confirm it’s not there.

Space Complexity: O(1)

You only need a few variables—like left, right, and mid. That’s it. No extra memory needed.

Pros of Binary Search

  • Super fast for large, sorted data.
  • Simple to implement once you get the hang of it.
  • Works great in many real-world use cases.

But There Are a Few Limitations

  • The list has to be sorted. If it’s not, binary search won’t work.
  • Not ideal for linked lists or structures without random access.

Where Do We Use Binary Search?

It’s everywhere—from searching names in a contact list, finding a word in a dictionary, optimizing algorithms, to narrowing down answers in coding problems.

Tips for Success

  • Always check if the list is sorted first.
  • Watch out for off-by-one errors—common in binary search.
  • Use test cases with 1 or 2 elements to test your logic.

Binary vs Linear Search

Binary search is fast but needs sorted data. Linear search checks one-by-one, slower for big lists but works on anything. Use binary search when speed matters and you know your data is in order.

FAQs

Can I use binary search on unsorted data?

Nope, the data has to be sorted for binary search to work correctly.

What if the number isn’t in the array?

You’ll reach the end of the loop and return -1—it simply means it’s not there.

Can binary search work on a linked list?

Not really. Linked lists don’t give you direct access to the middle, so binary search is inefficient there.

Do all languages support binary search?

Pretty much. Either through built-in libraries or your own implementation, it’s doable in Java, Python, C++, and more.

How can I avoid bugs when coding binary search?

Test edge cases, double-check your math on mid, and watch the loop condition. Practice helps a lot!

In a Nutshell

Binary search is a must-know tool for every developer. It’s fast, reliable, and shows up all over tech problems. Master it once, and you’ll use it forever.

Approach 2: Find Upper bound

Intuition

Here we introduce an alternative way to implement binary search: instead of looking for target in the array nums, we look for the insert position where we can put target in without disrupting the order.

Generally, we have two inserting ways, insert into the rightmost possible position which we called finding the upper bound, and insert into the leftmost possible position which we called finding the lower bound. We will implement them in the following approaches.

Take the picture below as an example. Assume that we want to insert 9 into array A. If we look for the upper bound, we have to insert 9 to the right of all existing 9s in the array. Similarly, if we look for the lower bound, we have to insert 9 to the left of all existing 9s. (Although we don't have duplicate elements in this problem, having duplicate elements is more common in problems so we would better know this concept in advance!)

Now we start the binary search. Similar to the previous approach, we still use left and right as two boundary indexes. The question is, what is the next step after we find the middle index mid?

1. If nums[mid] < target, the insert position is on mid's right, so we let left = mid + 1 to discard the left half and mid. 2. If nums[mid] = target, the insert position is on mid's right, so we let left = mid + 1 to discard the left half and mid. 3. If nums[mid] > target, mid can also be the insert position. So we let right = mid to discard the right half while keeping mid. Therefore, we merged the two conditions nums[mid] = target and nums[mid] < target and there are only two conditions in the if-else statement!

Once the loop stops, left stands for the insert position and left - 1 is the largest element that is no larger than target. We just need to check if nums[left - 1] equals target. Note this boundary condition where left = 0, which means all elements in nums are larger than target, so there is no target in nums.

Algorithm

  1. Initialize the boundaries of the search space: left = 0 and right = nums.size

    Note: The maximum insert position can be nums.size.

  2. While there are elements in the range [left, right]:
    • Find the middle index: mid = (left + right) / 2.
    • Compare nums[mid] with target:
      • If nums[mid] <= target, set left = mid + 1 and repeat step 2.
      • If nums[mid] > target, set right = mid and repeat step 2.
  3. When the loop ends, left represents the insert position:
    • If left > 0 and nums[left - 1] == target, return left - 1.
    • Otherwise, return -1.

Here’s the Java Code


  
  class Solution {
    public int search(int[] nums, int target) {
        // Set the left and right boundaries
        int left = 0, right = nums.length;
        
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] <= target) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        
        if (left > 0 && nums[left - 1] == target) {
            return left - 1;
        } else {
            return -1;
        } 
    }
}

Complexity Analysis

Let n be the size of the input array nums.

Time Complexity: O(log n)

At each step, the array is divided in half. In the worst-case scenario, we continue splitting the range until there are no elements left. This results in a logarithmic number of steps, so the time complexity is O(log n).

Space Complexity: O(1)

The algorithm uses only a constant amount of space — it keeps track of just three variables: left, right, and mid. No extra memory is used that depends on the input size.

Approach 3: Find Lower bound

Intuition

This approach differs from the classic binary search because we’re specifically searching for the leftmost insert position of the target. To do this, we slightly change the logic in our condition checks:

  • If nums[mid] < target: Since mid could also be a valid insert position, we move left = mid + 1. This discards the left half, but keeps mid in play.
  • If nums[mid] = target or nums[mid] > target: The correct insert position lies to the left of mid, so we set right = mid, discarding both mid and the right half.

These two cases allow us to merge the conditions nums[mid] == target and nums[mid] > target into a single branch. So the if-else structure only has two conditions, making the logic concise and efficient.

When the loop ends, left represents the insert position, and nums[left] is the smallest element that is greater than or equal to the target.

Note: There’s a special boundary case when left == nums.length. This means every element in the array is smaller than the target, so target doesn’t exist in nums.

Algorithm

  1. Initialize the boundaries of the search space: left = 0 and right = nums.length (Note: the maximum insert position can be nums.length).
  2. While there are elements in the range [left, right):
    • Calculate the middle index: mid = (left + right) / 2.
    • Compare nums[mid] with target:
      • If nums[mid] >= target, set right = mid and repeat.
      • If nums[mid] < target, set left = mid + 1 and repeat.
  3. When the loop ends, left represents the insert position:
    • If left < nums.length and nums[left] == target, return left.
    • Otherwise, return -1.

Here’s the Java Code


class Solution {
    public int search(int[] nums, int target) {
        // Set the left and right boundaries
        int left = 0, right = nums.length;
        
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] >= target) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        
        if (left < nums.length && nums[left] == target) {
            return left;
        } else {
            return -1;
        } 
    }
} 

Complexity Analysis

Let n be the size of the input array nums.

Time Complexity: O(log n)

The array nums is divided in half with each iteration. In the worst-case scenario, we continue this process until the search range becomes empty. This logarithmic reduction leads to a time complexity of O(log n).

Space Complexity: O(1)

The algorithm only needs to track three variables: left, right, and mid, which means it uses a constant amount of space regardless of the input size.

Approach 4: Use built-in tools.

Intuition

After exploring different binary search templates, let’s take a quick look at a more convenient approach that uses built-in functions. Many programming languages offer libraries that simplify binary search.

For instance, C++ provides the <algorithm> library with functions like upper_bound and lower_bound. Similarly, Python has the bisect module with bisect_right and bisect_left. These tools are great for solving standard problems quickly without writing the entire binary search logic manually.

Here's what they do:

  • upper_bound in C++ and bisect.bisect_right in Python find the rightmost insertion position. This is similar to the second binary search approach.
  • lower_bound in C++ and bisect.bisect_left in Python find the leftmost insertion position. This matches the logic of the third binary search approach.

Once you determine the insertion position using these built-in tools, simply check if the value at that position matches the target.

In this explanation, we’ll demonstrate the method using upper_bound or bisect.bisect_right. Try implementing the alternative with lower_bound or bisect.bisect_left as a practice challenge!

Algorithm

  1. Use built-in tools such as upper_bound in C++ or bisect.bisect_right in Python to find the rightmost insertion position idx.
  2. Check the element before this position:
    • If idx > 0 and nums[idx - 1] == target, then the target was found — return idx - 1.
    • Otherwise, return -1 to indicate the target is not present.

Here’s the Java Code


class Solution {
public:
    int search(vector& nums, int target) {
        // Find the insertion position `idx`.
        int idx = upper_bound(nums.begin(), nums.end(), target) - nums.begin();

        if (idx > 0 && nums[idx - 1] == target) {
            return idx - 1;
        } else {
            return -1;
        }    
    }
};

Complexity Analysis

Let n be the size of the input array nums.

Time Complexity: O(log n)

The time complexity of the built-in binary search is O(log n) since it divides the search space in half at each step.

Space Complexity: O(1)

The built-in binary search uses only a constant amount of memory, hence the space complexity is O(1).

Continue Reading →