logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
13. Roman to Integer14. Longest Common Prefix20. Valid Parentheses26. Remove Duplicates from Sorted Array35. Search Insert Position69. Sqrt(x)70. Climbing Stairs88. Merge Sorted Array (In-Place)104. Maximum Depth of Binary Tree118. Pascal's Triangle121. Best Time to Buy and Sell Stock205. Isomorphic Strings242. Valid Anagram283. Move Zeroes345. Reverse Vowels of a String605. Can Place Flowers704. Binary Search796. Rotate String1071. Greatest Common Divisor of Strings1299. Replace Elements with Greatest Element on Right Side1431. Kids With the Greatest Number of Candies1614. Maximum Nesting Depth of the Parentheses1752. Check if Array Is Sorted and Rotated1768. Merge Strings Alternately1903. Largest Odd Number in String2965. Find Missing and Repeated Values
Code Scratch/leetcode/easy

704. Binary Search

1 min read
On this pageIntitution
IntitutionComplexityCode

# Intitution

Given a sorted array, and we need to find the index of a target element efficiently.

Since the array is sorted in ascending order, we can use Binary Search, which divides the array in half every time, reducing time complexity from O(n)\text{O}(n)O(n) to O(nlog⁡n)\text{O}(n\log{n})O(nlogn)

# Complexity

Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(nlog⁡n)\text{O}(n\log{n})O(nlogn)

# Code

public int search(int[] nums, int target) {
    
    // Edge case: only one element
    if (nums.length == 1) return nums[0] == target ? 0 : -1;
 
    int left = 0, right = nums.length - 1;
 
    while (left <= right) {
        int mid = (left + right) >> 1; // Efficient way to get mid = (left + right) / 2
 
        if (nums[mid] == target) return mid; // Found target
 
        if (nums[mid] > target) {
            right = mid - 1; // Target is in the left half
        } else {
            left = mid + 1; // Target is in the right half
        }
    }
 
    return -1; // Target not found
}
←Previous605. Can Place FlowersNext→796. Rotate String

On this page

IntitutionComplexityCode