Begin Algo
Searching & Two Pointers · Comparison

Search and two-pointer techniques compared

Linear search, binary search, binary search on the answer, two pointers and sliding window: what each one requires and which problem shape it solves.

AlgorithmTimeSpaceRequiresAnswersDifficulty
Linear SearchLinear searchO(n)O(1)NothingIs x here, and whereIntro
Binary SearchBinary searchO(log n)O(1)Sorted, random accessPosition of x, first position ≥ xIntro
Binary Search on AnswerBinary search on the answerO(n log R)O(1)Monotonic answerSmallest or largest feasible valueHard
Two PointersTwo pointersO(n)O(1)Sorted, or ends that convergePairs, dedupe, partitionIntermediate
Sliding WindowSliding windowsO(n)O(k)Contiguous range, incrementally maintainableLongest, shortest or count of subarraysIntermediate

When to pick which

Choosing guide

  • Sorted + one value or boundary → binary search. Sorted + a pair → two pointers.
  • The word 'contiguous' appears → sliding window. A subsequence (non-contiguous) is not a window; it is usually DP.
  • Asks for the smallest or largest feasible value, not a position → binary search on the answer. Cues: 'minimum needed', 'maximum achievable', 'minimise the maximum'.
  • The window condition cannot be updated in O(1) (window median, say) → sliding window alone is not enough; add a monotonic deque, a balanced tree or two heaps.
  • Unsorted but queried often → not a search-algorithm problem: sort once (O(n log n)) or use a hash table (O(1) per query).