DEV Community

Cover image for Multiple Pointers | C#
Andres Ramirez
Andres Ramirez

Posted on

Multiple Pointers | C#

What is this all about?

  • Used for searching pairs in a SORTED array
  • Create pointers that correspond to an index and move towards the beginning, end or middle based on a certain condition.
  • We are able to process two or more elements per loop instead of just one.

When do we use it?

  • In many problems involving collections such as arrays or lists, we have to analyze each element of the collection compared to its other elements.

Common patterns

  • Two pointers, each starting from the beginning and the end until they both meet.
  • One pointer moving at a slow pace, while the other pointer moves at twice the speed.
--- Problem
    We are asked to compare two elements in an ordered array.

--- FOOR LOOP
     If we use a for loop, we create an external pointer and use the 
     internal "j" as the second pointer.
         var i = 0;          
         for(var j = 1; j < array.length; j++){  
                if(arr[i] !== arr[j]){
                    i++; 
                    arr[i] = arr[j]
                }

--- WHILE LOOP
    If we use a while loop we create two external pointers and the  
    base one case is while left<right {}. This structure is used when 
    we need to traverse the array from two opposite points. 

        let left = 0                       <-- pointer 1
        let right = array.length - 1       <-- pointer 2
        while (left < right) {
            let average = array[left] + array[right] / 2 
            if (average === target) return true; 
            else if(average < target) left++
            else right--  
        }
        return false 
    }
Enter fullscreen mode Exit fullscreen mode

In action

Implement a function called countUniqueValues, which accepts a sorted array, and counts the unique values in the array.

Code to resolve this:
Ex1 Solution

Top comments (0)