Menu

1 / 2

Two Pointer Technique in Java: The Trick That Replaces Nested Loops

DEV Community·Quipoin·6 months ago
#j0AXRhle
#coding#database#programming#ai#left
Reading 0:00
15s threshold

Many array problems look like they need nested loops.

That means O(n²) time.

But with one simple idea — Two Pointers —

you can often reduce it to O(n).

What is Two Pointer Technique?

Instead of using one loop,

you use two indices (pointers):

From opposite ends

Or moving in the same direction

Helps reduce unnecessary work

Example 1: Two Sum (Sorted Array)

public static int[] twoSumSorted(int[] arr, int target) {

int left = 0, right = arr.length - 1;

while (left < right) { int sum = arr[left] + arr[right];

if (sum == target) return new int[]{left, right}; else if (sum < target) left++; else right--; }

return new int[]{-1, -1};

Enter fullscreen mode

Exit fullscreen mode

}

Idea:

If sum is small → move left

If sum is large → move right

Example 2: Remove Duplicates

public static int removeDuplicates(int[] arr) {

if (arr.length == 0) return 0;

int writeIndex = 1;

for (int readIndex = 1; readIndex < arr.length; readIndex++) { if (arr[readIndex] != arr[readIndex - 1]) { arr[writeIndex++] =…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.