MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Two-Pointer Technique: Opposite-Direction & Fast-Slow Patterns0%
Study Materials
Data Structures & AlgorithmsProgress 0%
1.1Introduction to DSA, Big-O, Big-Omega & Big-Theta Notations1.2Time Complexity Calculation Rules & Common Runtime Patterns1.3Space Complexity, Auxiliary Memory & Stack vs Heap Allocation
2.1Static vs Dynamic Arrays, Amortized O(1) Operations & Memory Locality2.2Two-Pointer Technique: Opposite-Direction & Fast-Slow Patterns2.3Sliding Window Algorithm: Fixed & Dynamic Window Strategies2.4Prefix Sums & Difference Arrays for Constant-Time Range Queries
HomeTutorialsData Structures & AlgorithmsTwo-Pointer Technique: Opposite-Direction & Fast-Slow Patterns
Sliding Window Algorithm: Fixed & Dynamic Window Strategies

Two-Pointer Technique: Opposite-Direction & Fast-Slow Patterns

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

The Two-Pointer Technique is an algorithmic pattern that uses two pointer indices to coordinate searches or mutations across an array or sequence. By moving pointers intelligently based on problem constraints, two-pointer algorithms reduce brute-force $O(n^2)$ quadratic nested loops into blazing $O(n)$ linear time with $O(1)$ auxiliary space.


1. Real-World Analogy: Folding a Ruler or Reading a Word

Imagine inspecting whether a word like "RADAR" is a palindrome:

  • You don't make a second copy of the word and check every combination.
  • Instead, you place your left index finger on the first letter 'R' and your right index finger on the last letter 'R'.
  • You verify they match, then slide your fingers inward simultaneously. If your fingers meet in the middle without any mismatches, it is a palindrome!

2. The Two Core Categories of Two Pointers

Category 1: Opposite-Direction Pointers (Converging)

  • Pointer left starts at index 0.
  • Pointer right starts at index n - 1.
  • Pointers advance towards each other (left++, right--) until they meet.
  • Top Applications: Reversing arrays, Palindrome checking, Two Sum in Sorted Array, Container with Most Water.

Category 2: Same-Direction Pointers (Fast & Slow)

  • Pointer slow tracks the boundary of clean/valid data.
  • Pointer fast scans forward through the array.
  • Top Applications: In-place element removal, deduplicating sorted arrays, moving zeros.

3. Classic Problem 1: Two Sum in a Sorted Array ($O(n)$)

Given a 1-indexed array of integers numbers sorted in non-decreasing order, find two numbers such that they add up to a specific target number:

1Array: [2, 7, 11, 15], Target = 18
2Left = 0 (val 2), Right = 3 (val 15) -> Sum = 17 (< 18, so increment Left!)
3Left = 1 (val 7), Right = 3 (val 15) -> Sum = 22 (> 18, so decrement Right!)
4Left = 1 (val 7), Right = 2 (val 11) -> Sum = 18 (Target MATCH!)

Python 3 Implementation:

1def two_sum_sorted(numbers: list[int], target: int) -> list[int]:
2 left, right = 0, len(numbers) - 1
3
4 while left < right:
5 current_sum = numbers[left] + numbers[right]
6 if current_sum == target:
7 return [left + 1, right + 1] # 1-based index
8 elif current_sum < target:
9 left += 1 # Need a larger sum -> move left pointer right
10 else:
11 right -= 1 # Need a smaller sum -> move right pointer left
12
13 return []

Modern JavaScript / TypeScript Implementation:

1export function twoSumSorted(numbers: number[], target: number): number[] {
2 let left = 0;
3 let right = numbers.length - 1;
4 
5 while (left < right) {
6 const sum = numbers[left] + numbers[right];
7 if (sum === target) {
8 return [left + 1, right + 1];
9 } else if (sum < target) {
10 left++;
11 } else {
12 right--;
13 }
14 }
15 
16 return [];
17}

4. Classic Problem 2: Remove Duplicates from Sorted Array In-Place

Remove duplicates in-place such that each unique element appears only once, returning the count of unique items.

Python 3:

1def remove_duplicates(nums: list[int]) -> int:
2 if not nums:
3 return 0
4
5 write_idx = 1 # Slow pointer: position to write next unique element
6
7 for read_idx in range(1, len(nums)): # Fast pointer scans forward
8 if nums[read_idx] != nums[read_idx - 1]:
9 nums[write_idx] = nums[read_idx]
10 write_idx += 1
11
12 return write_idx

5. Trace Table: nums = [1, 1, 2, 2, 3]

read_idx (Fast)Current ValuePrevious ValueIs Unique?ActionModified Array
111NoSkip[1, 1, 2, 2, 3]
221Yesnums[1] = 2, write++[1, 2, 2, 2, 3]
322NoSkip[1, 2, 2, 2, 3]
432Yesnums[2] = 3, write++[1, 2, 3, 2, 3]

Result: First 3 elements are [1, 2, 3]. Return length 3 in $O(n)$ time with $O(1)$ space!


Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What prerequisite condition is typically required to apply the opposite-direction Two-Pointer technique for the Two Sum problem?
Question 2
What is the time and space complexity of the Two-Pointer Two Sum solution on an already sorted array of size $n$?
Question 3
In the Fast & Slow pointer pattern for removing duplicates in-place, what does the "slow" pointer track?
Question 4
Which of the following classic LeetCode/interview problems is optimally solved using converging Two Pointers?
Question 5
Why is the Two-Pointer approach preferred over a nested loop for checking if a string is a palindrome?

Next Lesson

Sliding Window Algorithm: Fixed & Dynamic Window Strategies

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Static vs Dynamic Arrays, Amortized O(1) Operations & Memory LocalitySliding Window Algorithm: Fixed & Dynamic Window Strategies

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Data Structures & Algorithms with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext