⚡ TL;DR
Binary search a sorted array in Dart with working code. Iterative approach with O(log n) time, plus complexity analysis and interview tips.
Binary Search (#704 — Easy): Given an array of integers nums sorted in ascending order and an integer target, return the index of target in nums, or -1 if it is not present.
Problem Statement
Given an array of integers nums sorted in ascending order and an integer target, return the index of target in nums, or -1 if it is not present.
Example:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists at index 4.Approach: Iterative Two Pointers
Time: O(log n) | Space: O(1)
Keep lo and hi pointers on the search window. Compare the middle element with the target, discard the half that cannot contain it, and stop when the window closes — or the target is found.
int binarySearch(List<int> nums, int target) {
int lo = 0, hi = nums.length - 1;
while (lo <= hi) {
int mid = (lo + hi) ~/ 2;
if (nums[mid] == target) {
return mid;
}
if (nums[mid] < target) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return -1;
}
void main() {
List<int> nums = [-1, 0, 3, 5, 9, 12];
print('Index of 9: ${binarySearch(nums, 9)}');
print('Index of 2: ${binarySearch(nums, 2)}');
}Approach: Recursive Divide & Conquer
Time: O(log n) | Space: O(log n)
The same halving expressed as recursion: search the left or right half until the window is empty. Same comparisons, but the call stack stores log n frames.
int binarySearchRecursive(List<int> nums, int target, int lo, int hi) {
if (lo > hi) {
return -1;
}
int mid = (lo + hi) ~/ 2;
if (nums[mid] == target) {
return mid;
}
if (nums[mid] < target) {
return binarySearchRecursive(nums, target, mid + 1, hi);
}
return binarySearchRecursive(nums, target, lo, mid - 1);
}
void main() {
List<int> nums = [-1, 0, 3, 5, 9, 12];
print('Index of 9: ${binarySearchRecursive(nums, 9, 0, nums.length - 1)}');
print('Index of 2: ${binarySearchRecursive(nums, 2, 0, nums.length - 1)}');
}Key Takeaways
- mid = (lo + hi) // 2 — integer division avoids float indices in every language
- The loop condition lo <= hi (not <) is the classic off-by-one trap
- Halving the window each step is what turns 1,000,000 elements into ~20 comparisons
FAQ
What is the best approach to solve Binary Search in Dart?
The recommended approach is Iterative Two Pointers, which runs in O(log n) time with O(1) space. The full Dart implementation is shown above.
What is the time complexity of Binary Search in Dart?
Using Iterative Two Pointers, the time complexity is O(log n) and the space complexity is O(1); Recursive Divide & Conquer runs in O(log n) time with O(log n) space.
Happy coding!

Written by Mihir Pipermitwala
Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.
More about Mihir →