Skip to content
DSA searching 5 min read

Searching Exercises: Binary Search & Two-Pointers Practice

Time to practice. Solve each problem yourself first — write the code, trace a small example by hand, and reason about its time and space complexity. Only then open the answer sheet. Every View answer link jumps to a full, multi-language solution on the searching solutions page.

How to practice: Set a timer (15–25 min per problem). If you’re stuck, re-read binary search or two pointers before peeking. The boundary and feasibility templates are the whole game here — internalize them.

Warm-ups

Q1. Binary search. Given a sorted array a and a target, return the index of target, or -1 if it’s absent. Target O(log n) time, O(1) space. Make your midpoint overflow-safe.

View answer →

Q2. Search insert position. Given a sorted array and a target, return the index where target is (if present) or where it would be inserted to keep the array sorted. O(log n).

View answer →

Core problems

Q3. Count occurrences of a value. A sorted array may contain duplicates. Return how many times target appears. Must be O(log n) — no linear scan.

View answer →

Q4. Two Sum II (sorted input). Given a sorted array and a target, return the indices of two distinct elements that sum to target (assume exactly one solution). Aim for O(n) time and O(1) extra space.

View answer →

Q5. Integer square root. Given a non-negative integer n, return floor(sqrt(n)) using only integer arithmetic — no sqrt/pow. Target O(log n).

View answer →

Challenge

Q6. Find minimum in a rotated sorted array. A sorted array of distinct values was rotated at some unknown pivot (e.g. [4,5,6,7,0,1,2]). Return the minimum element in O(log n).

View answer →

Q7. Capacity to ship packages within D days. Given package weights[] (in load order) and days, find the minimum ship capacity so all packages ship within days, loading in order without splitting a package. Use binary search on the answer.

View answer →


Done? Review every solution on the searching answer sheet — even the ones you solved, since there’s often a cleaner boundary template. Then continue to sliding window.

Last updated June 25, 2026
Was this helpful?