LeetCode 704: Binary Search
Solving LeetCode 704: A Guide to Binary Search
I'm Varchasv, a Data Engineer working on enterprise data integration.
Currently on a 90-problem challenge to level up my technical skills and switch to a more development-focused role.
What I'm doing:
- Solving 2 Leetcode problems daily (SQL + DSA).
- Blogging about each problem.
- Building in public.
My Goal - Land a better data engineering role by mid-2026.
Follow my journey !!
Date: February 02, 2026
Category: Arrays | Binary Search
Time Taken: 15 minutes
Difficulty: Easy
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.
Link: Binary Search
Solution 1 (HashMap):
We could use a HashMap to associate each value with its index.
Then, we can check if the target is in the HashMap. If it is, we return the index; if not, we return -1.
This solution is not Not O(logN).
Solution Code
class Solution:
def search(self, nums: List[int], target: int) -> int:
seen = {}
for index, value in enumerate(nums):
seen[value] = index
if target in seen:
return seen[target]
return -1
Complexity:
Time: O(N) Space: O(N)
Solution 2 (Binary Search) [Optimized]:
The proper solution is to write a Binary Search algorithm. We will start with two pointers:
leftandright.While
left <= right, we will define a variablemiddleasleft + (right - left) // 2. We use//instead of/to ensure we get whole numbers, not decimals.If the target is smaller than
middle, we will moverighttomiddle - 1. If the target is larger thanmiddle, we will movelefttomiddle + 1. If neither is true, it meansmiddleequals the target, and we will return themiddleindex.
Solution Code (No separate arrays)
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
while left <= right:
middle = left + (right - left) // 2
if target > nums[middle]:
left = middle + 1
elif target < nums[middle]:
right = middle - 1
else:
return middle
return -1
Complexity:
Time: O(logN) Space: O(1)
Key Takeaway: How Binary Search in written in Python.
Pattern: Binary Search
Series: 90 Days of Data Engineering Progress: 29/90 problems completed
Tags: #DEQuest #LeetCode #Python #DataEngineering #BuildInPublic