Skip to main content

Bisect in a Loop

An outer loop walks items or rows; each step bisects a sorted structure. The bisect is the same primitive from Foundations; the loop around it is the problem.

Cost: n log m​

n outer steps times one O(log m) bisect each. Sorting the searched side first adds O(m log m) once.

for x in items:
i = bisect_left(sorted_side, partner(x))
if i < len(sorted_side) and sorted_side[i] == partner(x):
...

When two pointers beat it​

If both sides are sorted and the partner only moves one way as x grows, two pointers do the same job in O(n + m). Bisect wins when one side is much smaller, or when the searched side is not walked in order.

Find the partner​

Loop x, bisect for target - x, 2x, c - a * a, or the last b[j] >= a[i].

167. Two Sum II - Input Array Is Sorted​

167. Two Sum II - Input Array Is Sorted

LeetCode
Medium

Fix One, Bisect Another

FIG. 167 TWO SUM II INPUT ARRAY IS SORTED 2● INTERACTIVE
visualization loads as you reach it
class Solution:
def bisect_left(self, arr, target, lo: int = 0, hi: int = None):
# hi is exclusive. The insert position can never be >= len(arr)
hi = (hi or len(arr)) - 1
if lo == hi + 1: # if array is empty
return -1
if arr[hi] < target:
return hi + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
def twoSum(self, numbers: List[int], target: int) -> List[int]:
for i in range(len(numbers)):
find = target - numbers[i]
j = self.bisect_left(numbers, find, lo=i + 1, hi=len(numbers))
if j < len(numbers) and numbers[j] == find:
return [i + 1, j + 1]
return [-1, -1]
top ↑

16. 3Sum Closest​

16. 3Sum Closest

LeetCode
Medium

Sort + Fix Two, Bisect the Third

FIG. 16 3SUM CLOSEST BISECT● INTERACTIVE
visualization loads as you reach it
class Solution:
def threeSumClosest(self, nums: list[int], target: int) -> int:
nums.sort()
ans = float("inf")
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
comp = target - nums[i] - nums[j]
idx = bisect.bisect_left(nums, comp, j + 1, n)
for k in [idx, idx - 1]:
if j < k < n:
total = nums[i] + nums[j] + nums[k]
if abs(target - ans) > abs(target - total):
ans = total
return ans

Every approach

ApproachTimeWhen an interviewer wants it
Aux space
Brute ForceO(n3)opening line
O(1)
Sort + Fix Two, Bisect the ThirdO(n2 log n)"without two pointers"
O(sort)
Sort + 2 Converging PointersO(n2)the expected answer
O(sort)
Hash mapdoes not work"why no hash version?": hashing answers exact membership, not nearest
-
top ↑

1099. Two Sum Less Than K​

1099. Two Sum Less Than K

LeetCode
Easy

Given an array nums of integers and an integer k, return the maximum sum such that there exists i < j with nums[i] + nums[j] = sum and sum < k. If no i, j exist satisfying this equation, return -1.

  • nums = [34, 23, 1, 24, 75, 33, 54, 8], k = 60 returns 58: 34 + 24.
  • nums = [10, 20, 30], k = 15 returns -1: no pair sums below 15.
  • Constraints: 1 <= nums.length <= 100, 1 <= nums[i] <= 1000, 1 <= k <= 2000.

Brute Force

FIG. 1099 TWO SUM LESS THAN K BRUTE FORCE● INTERACTIVE
visualization loads as you reach it
class Solution:
def twoSumLessThanK(self, nums: list[int], k: int) -> int:
n = len(nums)
ans = -1
for i in range(n):
for j in range(i + 1, n):
total = nums[i] + nums[j]
if total < k:
ans = max(ans, total)
return ans

Every approach

ApproachTimeWhen an interviewer wants it
Aux space
Brute ForceO(n2)opening line
O(1)
Sort + Fix One, Bisect AnotherO(n log n)"without two pointers"
O(sort)
Sort + 2 Converging PointersO(n log n)the expected answer
O(sort)
Count by ValueO(n + D2)when the small value range is the point
O(D)
top ↑

259. 3Sum Smaller​

259. 3Sum Smaller

LeetCode
Medium

Brute Force

FIG. 259 3SUM SMALLER BRUTE FORCE● INTERACTIVE
visualization loads as you reach it
class Solution:
def threeSumSmaller(self, nums: list[int], target: int) -> int:
n = len(nums)
ans = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if nums[i] + nums[j] + nums[k] < target:
ans += 1
return ans

Every approach

ApproachTimeWhen an interviewer wants it
Aux space
Brute ForceO(n3)opening line
O(1)
Sort + Fix Two, Bisect the ThirdO(n2 log n)"without two pointers"
O(sort)
Sort + 2 Converging PointersO(n2)the expected answer, and the common follow-up to 3Sum
O(sort)
top ↑

611. Valid Triangle Number​

611. Valid Triangle Number

LeetCode
Medium

Brute Force

FIG. 611 VALID TRIANGLE NUMBER BRUTE FORCE● INTERACTIVE
visualization loads as you reach it
class Solution:
def triangleNumber(self, nums: list[int]) -> int:
nums.sort()
n = len(nums)
ans = 0
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
if nums[i] + nums[j] > nums[k]:
ans += 1
return ans

Every approach

ApproachTimeWhen an interviewer wants it
Aux space
Brute ForceO(n3)opening line
O(sort)
Sort + Fix Two, Bisect the ThirdO(n2 log n)"without two pointers"
O(sort)
Sort + Fix Largest + 2 Converging PointersO(n2)the expected answer
O(sort)
top ↑

18. 4Sum​

18. 4Sum

LeetCode
Medium

Brute Force

FIG. 18 4SUM BRUTE FORCE● INTERACTIVE
visualization loads as you reach it
class Solution:
def fourSum(self, nums: list[int], target: int) -> list[list[int]]:
n = len(nums)
seen = set()
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
for l in range(k + 1, n):
if nums[i] + nums[j] + nums[k] + nums[l] == target:
seen.add(tuple(sorted((nums[i], nums[j], nums[k], nums[l]))))
return list(seen)

Every approach

ApproachTimeWhen an interviewer wants it
Aux space
Brute ForceO(n4)opening line
O(Q)
Fix Two + 1-Pass Index MapO(n3)when the input can't be sorted
O(n + Q)
Sort + Fix Three, Bisect the FourthO(n3 log n)"without two pointers"
O(sort + Q)
Sort + Fix Two + 2 Converging PointersO(n3)the expected answer
O(sort)
Recursive kSumO(nk-1)"how would you do 5Sum?"
O(k + sort)
top ↑

1346. Check If N and Its Double Exist​

1346. Check If N and Its Double Exist

LeetCode
Easy

Check Every Pair

FIG. 1346 CHECK IF N AND ITS DOUBLE EXIST BRUTE FORCE● INTERACTIVE
visualization loads as you reach it
class Solution:
def checkIfExist(self, arr: list[int]) -> bool:
n = len(arr)
for i in range(n):
for j in range(n):
if i != j and arr[i] == 2 * arr[j]:
return True
return False
top ↑

1385. Find the Distance Value Between Two Arrays​

1385. Find the Distance Value Between Two Arrays

LeetCode
Easy

Check Every Pair

FIG. 1385 FIND THE DISTANCE VALUE BETWEEN TWO ARRAYS BRUTE FORCE● INTERACTIVE
visualization loads as you reach it
class Solution:
def findTheDistanceValue(self, arr1: list[int], arr2: list[int], d: int) -> int:
count = 0
for a in arr1:
for b in arr2:
if abs(a - b) <= d:
break
else:
count += 1
return count
top ↑

2154. Keep Multiplying Found Values by Two​

2154. Keep Multiplying Found Values by Two

LeetCode
Easy

Sort then Bisect

FIG. 2154 KEEP MULTIPLYING FOUND VALUES BY TWO● INTERACTIVE
visualization loads as you reach it
class Solution:
def findFinalValue(self, nums: list[int], original: int) -> int:
nums.sort()
while True:
idx = bisect.bisect_left(nums, original, hi=len(nums) - 1)
if original == nums[idx]:
original *= 2
else:
return original
top ↑

633. Sum of Square Numbers​

633. Sum of Square Numbers

LeetCode
Medium

Enumerate a, Test the Complement

FIG. 633 SUM OF SQUARE NUMBERS● INTERACTIVE
visualization loads as you reach it
class Solution:
def isPerfectSquare(self, num: int) -> bool:
square = lambda i: i * i
# Answers [0, num]: lo lands one past the root, so step back unless square(lo) == num
lo, hi = 0, num
while lo < hi:
mid = lo + (hi - lo) // 2
if square(mid) <= num:
lo = mid + 1
else:
hi = mid
lo = lo if square(lo) == num else lo - 1
return square(lo) == num
def judgeSquareSum(self, c: int) -> bool:
for a in range(0, int(c**0.5) + 1):
b = c - a * a
if self.isPerfectSquare(b):
return True
return False
top ↑

1855. Maximum Distance Between a Pair of Values​

1855. Maximum Distance Between a Pair of Values

LeetCode
Medium

Without Reversing

FIG. 1855 MAXIMUM DISTANCE BETWEEN A PAIR OF VALUES 1● INTERACTIVE
visualization loads as you reach it
class Solution:
def bisect_right_rev(self, arr, target, lo: int = 0, hi: int = None):
# hi is inclusive. The insert position of the new element can be at the end of the list with index=len(arr)
hi = hi or len(arr)
if lo == hi: # if array is empty
return -1
if arr[hi - 1] > target:
return hi
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] >= target:
lo = mid + 1
else:
hi = mid
return lo
def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:
maxi = 0
for i, a in enumerate(nums1):
j = self.bisect_right_rev(nums2, a)
maxi = max(maxi, j - i - 1)
return maxi
top ↑

Common elements​

Walk the first array (or row) and bisect every other one for the same value.

349. Intersection of Two Arrays​

349. Intersection of Two Arrays

LeetCode
Easy

Bisect Each Element

FIG. 349 INTERSECTION OF TWO ARRAYS● INTERACTIVE
visualization loads as you reach it
class Solution:
def bisect_left(self, arr, target, lo: int = 0, hi: int = None):
# hi is exclusive. The insert position can never be >= len(arr)
hi = (hi or len(arr)) - 1
if lo == hi + 1: # if array is empty
return -1
if arr[hi] < target:
return hi + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
ans = []
prev = None
for num in nums1:
if num == prev:
continue
index = self.bisect_left(nums2, num)
if index < len(nums2) and nums2[index] == num:
ans.append(num)
prev = num
return ans
top ↑

350. Intersection of Two Arrays II​

350. Intersection of Two Arrays II

LeetCode
Easy

Bisect and Consume

FIG. 350 INTERSECTION OF TWO ARRAYS II● INTERACTIVE
visualization loads as you reach it
class Solution:
def bisect_left(self, arr, target, lo: int = 0, hi: int = None):
# hi is exclusive. The insert position can never be >= len(arr)
hi = (hi or len(arr)) - 1
if lo == hi + 1: # if array is empty
return -1
if arr[hi] < target:
return hi + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
ans = []
for num in nums1:
index = self.bisect_left(nums2, num)
print(index, nums2)
if 0 <= index < len(nums2) and nums2[index] == num:
nums2.pop(index)
ans.append(num)
return ans
top ↑

1198. Find Smallest Common Element in All Rows​

1198. Find Smallest Common Element in All Rows

LeetCode
Medium

Probe Every Other Row

FIG. 1198 FIND SMALLEST COMMON ELEMENT IN ALL ROWS● INTERACTIVE
visualization loads as you reach it
class Solution:
def bisect_left(self, arr, target, lo: int = 0, hi: int = None):
# hi is exclusive. The insert position can never be >= len(arr)
hi = (hi or len(arr)) - 1
if lo == hi + 1: # if array is empty
return -1
if arr[hi] < target:
return hi + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
def smallestCommonElement(self, mat: List[List[int]]) -> int:
for num in mat[0]:
found = True
for row in range(1, len(mat)):
index = self.bisect_left(mat[row], num)
if not (index < len(mat[row]) and mat[row][index] == num):
found = False
break
if found:
return num
return -1
top ↑

1213. Intersection of Three Sorted Arrays​

1213. Intersection of Three Sorted Arrays

LeetCode
Easy

Probe Every Other Array

FIG. 1213 INTERSECTION OF THREE SORTED ARRAYS● INTERACTIVE
visualization loads as you reach it
class Solution:
def bisect_left(self, arr, target, lo: int = 0, hi: int = None):
# hi is exclusive. The insert position can never be >= len(arr)
hi = (hi or len(arr)) - 1
if lo == hi + 1: # if array is empty
return -1
if arr[hi] < target:
return hi + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]:
mat = [arr1, arr2, arr3]
ans = []
for num in mat[0]:
found = True
for row in range(1, len(mat)):
index = self.bisect_left(mat[row], num)
if not (index < len(mat[row]) and mat[row][index] == num):
found = False
break
if found:
ans.append(num)
return ans
top ↑

2540. Minimum Common Value​

2540. Minimum Common Value

LeetCode
Easy

Bisect Each Element

FIG. 2540 MINIMUM COMMON VALUE BISECT● INTERACTIVE
visualization loads as you reach it
class Solution:
def getCommon(self, nums1: list[int], nums2: list[int]) -> int:
for i in nums1:
idx = bisect.bisect_left(nums2, i)
if idx < len(nums2) and i == nums2[idx]:
return i
return -1
top ↑

Row by row​

Each row is sorted on its own, so bisect each row for its boundary.

1351. Count Negative Numbers in a Sorted Matrix​

1351. Count Negative Numbers in a Sorted Matrix

LeetCode
Easy

Per-Row Upper-Bound (Manual Binary Search)

FIG. 1351 COUNT NEGATIVE NUMBERS IN A SORTED MATRIX 1● INTERACTIVE
visualization loads as you reach it
class Solution:
def countNegatives(self, grid: list[list[int]]) -> int:
m, n = len(grid), len(grid[0])
count = 0
for i in range(m):
# Answers [0, n]: a row with no negatives lands lo on n, giving n - lo = 0
lo, hi = 0, n
while lo < hi:
mid = lo + (hi - lo) // 2
if grid[i][mid] >= 0:
lo = mid + 1
else:
hi = mid
count += n - lo
return count
top ↑

1337. The K Weakest Rows in a Matrix​

1337. The K Weakest Rows in a Matrix

LeetCode
Easy

Count Soldiers, Keep K with a Heap

FIG. 1337 THE K WEAKEST ROWS IN A MATRIX● INTERACTIVE
visualization loads as you reach it
class Solution:
def bisect_left_rev(self, arr, target, lo: int = 0, hi: int = None):
# hi is exclusive. The insert position can never be >= len(arr)
hi = (hi or len(arr)) - 1
if lo == hi + 1: # if array is empty
return -1
if arr[hi] > target:
return hi + 1
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] > target:
lo = mid + 1
else:
hi = mid
return lo
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
max_heap = []
for row in range(len(mat)):
soldiers = self.bisect_left_rev(mat[row], 0)
# Put the strength/index pairs into a priority queue.
entry = (-soldiers, -row)
heapq.heappush(max_heap, entry)
if len(max_heap) > k:
heapq.heappop(max_heap)
ans = []
# Pull out and return the indexes of the smallest k entries.
# Don't forget to convert them back to positive numbers!
while max_heap:
ans.append(-heapq.heappop(max_heap)[1])
return ans[::-1] # Reverse, as the indexes are around the wrong way.
top ↑

1428. Leftmost Column with at Least a One​

1428. Leftmost Column with at Least a One

LeetCode
Medium

Custom Bisect per Row

FIG. 1428 LEFTMOST COLUMN WITH AT LEAST A ONE● INTERACTIVE
visualization loads as you reach it
class Solution:
def leftMostColumnWithOne(self, binaryMatrix: "BinaryMatrix") -> int:
def bisect_left(row):
# Answers [0, n): only called on rows ending in 1, so lo is the first 1
lo, hi = 0, n - 1
target = 1
while lo < hi:
mid = lo + (hi - lo) // 2
if binaryMatrix.get(row, mid) < target:
lo = mid + 1
else:
hi = mid
return lo
 
m, n = binaryMatrix.dimensions()
mini = n
for row in range(m):
if binaryMatrix.get(row, n - 1) != 0:
first_one = bisect_left(row)
mini = min(mini, first_one)
return mini if mini != n else -1
top ↑

Keep a sorted tail​

Bisect into an array you are building as you go.

300. Longest Increasing Subsequence​

300. Longest Increasing Subsequence

LeetCode
Medium

Binary Search, O(n log n)

FIG. 300 LONGEST INCREASING SUBSEQUENCE BISECT● INTERACTIVE
visualization loads as you reach it
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
sub = [nums[0]]
for num in nums[1:]:
if num > sub[-1]:
sub.append(num)
else:
ind = bisect.bisect_left(sub, num)
sub[ind] = num
return len(sub)
top ↑