Two pointer : Searching for Pairs or Subarrays

Dew
1 min readSep 27, 2023

--

Requirement: Understanding the Two Pointer Technique

Example :

fun main(){
var result = twoSumWithTwoPointerTechnique(intArrayOf(2,4,7,9,10),11)
println(result.toList())
}

fun twoSumWithTwoPointerTechnique(array:IntArray,target:Int):IntArray{
var startIndex = 0
var endIndex = array.size-1
while(startIndex<endIndex){
val sum = array[startIndex] + array[endIndex]
if(sum == target){
println("${array[startIndex]} + ${array[endIndex]} = $sum")
return intArrayOf(array[startIndex],array[endIndex])
}else if(sum<target){
startIndex ++
}else{
endIndex --
}
}
return intArrayOf()
}

Time Complexity for Sorted Array:

  • Two pointers that traverse the array once from both ends towards each other. The two pointers meet when they find the pair of elements that sum to the target, or they exhaust all possible pairs. In the worst case, both pointers traverse the entire array, leading to a linear time complexity of O(n).

Time Complexity for Un Sorted Array:

  • If the array is not already sorted, you would need to sort it first. Sorting typically has a time complexity of O(n log n) for algorithms like quicksort or mergesort. However, if the array is sorted or can be sorted in-place using an efficient algorithm like heapsort, this step can be done in O(n log n) time.

Thank you for reading , HAPPY CODING !!

--

--

Dew

Passionate Android developer with a deep interest in crafting elegant and efficient mobile applications. https://letmedo.in/