Javascript Program for Two Pointers Technique Last Updated : 16 Sep, 2024 Comments Improve Suggest changes Like Article Like Report Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X.Naive solution: JavaScript // Naive solution to find if there is a // pair in A[0..N-1] with given sum. function isPairSum(A, N, X) { for (let i = 0; i < N - 1; i++) { for (let j = i + 1; j < N; j++) { // as equal i and j means same element if (i == j) continue; // pair exists if (A[i] + A[j] == X) return 1; // as the array is sorted if (A[i] + A[j] > X) break; } } // No pair found with given sum. return 0; } // Driver code // array declaration let arr = [2, 3, 5, 8, 9, 10, 11]; // value to search let val = 17; // size of the array let arrSize = 7; // Function call console.log(isPairSum(arr, arrSize, val)); Output1 Time Complexity: O(n2).Efficieant Approach (Two Pointer Approach):Now let’s see how the two-pointer technique works. We take two pointers, one representing the first element and other representing the last element of the array, and then we add the values kept at both the pointers. If their sum is smaller than X then we shift the left pointer to right or if their sum is greater than X then we shift the right pointer to left, in order to get closer to the sum. We keep moving the pointers until we get the sum as X. JavaScript // Two pointer technique based solution to find // if there is a pair in A[0..N-1] with a given sum. function isPairSum(A, N, X) { // represents first pointer let i = 0; // represents second pointer let j = N - 1; while (i < j) { // If we find a pair if (A[i] + A[j] == X) return true; // If sum of elements at current // pointers is less, we move towards // higher values by doing i++ else if (A[i] + A[j] < X) i++; // If sum of elements at current // pointers is more, we move towards // lower values by doing j-- else j--; } return false; } // Driver code let arr = [2, 3, 5, 8, 9, 10, 11]; let val = 17; let arrSize = 7; let result = isPairSum(arr, arrSize, val); console.log(result); Outputtrue Illustration : Complexity Analysis:Time Complexity: O(n)Auxiliary Space: O(1) since using constant spaceHow does this work? The algorithm basically uses the fact that the input array is sorted. We start the sum of extreme values (smallest and largest) and conditionally move both pointers. We move left pointer i when the sum of A[i] and A[j] is less than X. We do not miss any pair because the sum is already smaller than X. Same logic applies for right pointer j.More problems based on two pointer technique. Find the closest pair from two sorted arraysFind the pair in array whose sum is closest to xFind all triplets with zero sumFind a triplet that sum to a given valueFind a triplet such that sum of two equals to third elementFind four elements that sum to a given valuePlease refer complete article on Two Pointers Technique for more details! Comment More infoAdvertise with us Next Article Javascript Program for Two Pointers Technique kartik Follow Improve Article Tags : Searching Technical Scripter JavaScript Web Technologies DSA Arrays two-pointer-algorithm +3 More Practice Tags : ArraysSearchingtwo-pointer-algorithm Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example 12 min read Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an 8 min read Like