Naieve way is a double for loop. A linear approach is two pointers on a sorted array, and check if addition of the current pairs is less than, equal to OR greater than target
.
Very important note: when you come across a valid pair, it’s not enough to just result += 1
, instead you should add all possible pairs in it result += right - left
.
Code
Python3
Big O Analysis
-
Runtime
The runtime complexity here is since we are visit all elements at most once.
-
Memory
The memory usage is since we do not use any data structures that grow with input size.
— A