Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Binary Search

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "704" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in nums and its index is 4 Example 2: Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in nums so return -1 Constraints: 1 <= nums.length <= 104 -104 < nums[i], target < 104 All the integers in nums are unique. nums is sorted in ascending order.

Explanation

  • Binary Search: The core idea is to leverage binary search, an efficient algorithm for finding a target value within a sorted array by repeatedly dividing the search interval in half.
    • Divide and Conquer: At each step, we compare the target value to the middle element of the current interval. If they match, we return the index. If the target is smaller, we narrow the search to the left half; otherwise, we search the right half.
    • Iterative Approach: We will use an iterative approach for the binary search to avoid potential stack overflow issues with very large arrays, which can sometimes happen with recursive implementations.
  • Runtime Complexity: O(log n), Storage Complexity: O(1)

Code

    def search(nums: list[int], target: int) -> int:
    """
    Searches for a target value in a sorted array using binary search.

    Args:
        nums: A sorted list of integers.
        target: The integer to search for.

    Returns:
        The index of the target if found, otherwise -1.
    """
    left, right = 0, len(nums) - 1

    while left <= right:
        mid = (left + right) // 2  # Integer division to find the middle index

        if nums[mid] == target:
            return mid
        elif nums[mid] < target:
            left = mid + 1  # Target is in the right half
        else:
            right = mid - 1  # Target is in the left half

    return -1  # Target not found

More from this blog

C

Chatmagic blog

2894 posts