The two-pointer technique is a simple and effective technique that is used in competitive programming. It helps programmer to efficiently solve array problem. In two-pointer we take two pointer at the start and the end. That pointers started to iterate the whole array and solve problem according to a programmer.
Suppose, we have an array n which consists m number of values. Now, if we want to sum all the element of the array then we have to iterate the whole array and sum all the element. Which will take O(n) time.
n = [4, 5, 2, 4, 9, 4]
But, in two-pointer technique we can solve this problem in O(n/2) time. Which is more efficient than traditional way.
In the code, we used two variable st which point at first element of the array and en which point at the last element of the array. After this, we take a while loop which condition is st should be less than en. If the condition does not meet the value, then loop will break. In the loop, we summed the first value and last value that are pointed. After that, we increases st variable value and decrease en values. By this technique, we can iterate the whole array in O(n) time.
Time Complexity: O(n)
Comments
Post a Comment