Arrays & Two Pointers Pattern - Master Your First DSA Pattern! ๐ฏ

Table of contents
- Why Arrays Matter in Coding Interviews
- Two Pointers Pattern: Your First Superpower ๐ฆธโโ๏ธ
- Pattern Deep Dive: Opposite Direction Two Pointers
- More Two Pointers Problems to Master
- When to Use Two Pointers Pattern
- Practice Schedule: Your Two Pointers Mastery Plan
- Essential Resources for Two Pointers
- Interview Tips: Ace Two Pointers Questions
- Key Takeaways
- Tomorrow's Preview: Sliding Window Pattern
- Your Action Items
- ๐ Success Metric
Welcome back to our LeetCode DSA Patterns mastery series! Today we're diving deep into Arrays and our first fundamental pattern: Two Pointers. This single pattern will help you solve 50+ LeetCode problems and is asked in interviews at Google, Amazon, Microsoft, and virtually every tech company.
If you missed our introduction yesterday, catch up here to understand the complete roadmap we're following.
Why Arrays Matter in Coding Interviews
Arrays are the most fundamental data structure and appear in approximately 40% of all coding interview questions. Before we dive into patterns, let's understand why mastering arrays is crucial:
๐ฏ Array Fundamentals You Must Know
Time Complexities:
Access: O(1)
Search: O(n)
Insertion: O(n)
Deletion: O(n)
Space Complexity: O(1) for in-place operations, O(n) for additional arrays
Key Operations:
Traversing, searching, sorting
Two-pointer techniques
Sliding window approaches
Prefix/suffix computations
Two Pointers Pattern: Your First Superpower ๐ฆธโโ๏ธ
The Two Pointers pattern is a technique where you use two pointers to traverse an array or string, typically to find pairs, triplets, or subarrays that satisfy certain conditions.
๐ What is Two Pointers?
Two Pointers is a versatile pattern that uses two indices to traverse data structures efficiently. Instead of using nested loops (O(nยฒ)), you can often solve problems in O(n) time.
Key Insight: When you need to find pairs of elements or compare elements from different positions, think Two Pointers!
๐ Why Two Pointers is Powerful
Reduces time complexity from O(nยฒ) to O(n)
Minimal space usage - typically O(1)
Intuitive approach - easy to understand and implement
Versatile application - works on arrays, strings, linked lists
๐ง Three Types of Two Pointers
1. Opposite Direction (Meet in Middle)
int left = 0;
int right = nums.size() - 1;
while (left < right) {
// Process nums[left] and nums[right]
left++;
right--;
}
2. Same Direction (Fast & Slow)
int slow = 0;
int fast = 0;
while (fast < nums.size()) {
// Process with slow and fast pointers
fast++;
// Move slow under certain conditions
}
3. Sliding Window (Dynamic Range)
int left = 0;
for (int right = 0; right < nums.size(); right++) {
// Expand window with right
while (condition_violated) {
// Shrink window with left
left++;
}
}
Pattern Deep Dive: Opposite Direction Two Pointers
Let's master this with a classic example:
๐ฏ Problem: Two Sum II - Input Array is Sorted
๐ Problem Link: LeetCode #167
๐ฅ Video Solutions:
NeetCode - Two Sum II Explained - Clear visual explanation
Deepti Talesra - Step by Step Walkthrough - Code explanation with examples
Eric Programming - Java Implementation - Two pointers technique
๐ Articles:
AlgoMonster - Two Sum II Detailed - In-depth explanation with complexity analysis
GeeksforGeeks - Two Sum Approach - Multiple approaches comparison
Problem Statement: Given a 1-indexed array of integers numbers
that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number.
๐ก C++ Solution
#include <vector>
using namespace std;
vector<int> twoSum(vector<int>& numbers, int target) {
/*
Find two numbers that add up to target in sorted array
Time: O(n), Space: O(1)
*/
int left = 0, right = numbers.size() - 1;
while (left < right) {
int current_sum = numbers[left] + numbers[right];
if (current_sum == target) {
return {left + 1, right + 1}; // 1-indexed
}
else if (current_sum < target) {
left++; // Need larger sum
}
else {
right--; // Need smaller sum
}
}
return {}; // No solution found
}
More Two Pointers Problems to Master
๐ข Easy Problems
1. Valid Palindrome
๐ Problem Link: LeetCode #125
๐ฅ Video Solutions:
NeetCode - Valid Palindrome - Two different approaches explained
Cracking FAANG - Valid Palindrome - Python solution walkthrough
๐ Articles:
- AlgoMonster - Valid Palindrome Guide - Complete explanation with examples
#include <string>
#include <cctype>
using namespace std;
bool isPalindrome(string s) {
/*Check if string is palindrome ignoring non-alphanumeric*/
int left = 0, right = s.size() - 1;
while (left < right) {
while (left < right && !isalnum(s[left])) left++;
while (left < right && !isalnum(s[right])) right--;
if (tolower(s[left]) != tolower(s[right])) {
return false;
}
left++;
right--;
}
return true;
}
2. Move Zeroes
๐ Problem Link: LeetCode #283
๐ฅ Video Solutions:
CodingNinja - Move Zeroes - Python solution with explanation
Study Algorithms - Move Zeroes - Full solution with examples
NeetCode - Move Zeroes - Visual approach
๐ Articles:
AlgoMonster - Move Zeroes - Detailed two-pointer explanation
GeeksforGeeks - Move Zeros Tutorial - Complete guide
#include <vector>
using namespace std;
void moveZeroes(vector<int>& nums) {
/*Move all zeros to end, maintain relative order*/
int write_index = 0;
// Move non-zero elements to front
for (int read_index = 0; read_index < nums.size(); read_index++) {
if (nums[read_index] != 0) {
nums[write_index] = nums[read_index];
write_index++;
}
}
// Fill remaining positions with zeros
while (write_index < nums.size()) {
nums[write_index] = 0;
write_index++;
}
}
๐ก Medium Problems
3. 3Sum
๐ Problem Link: LeetCode #15
๐ฅ Video Solutions:
NeetCode - 3Sum Explained - Step-by-step approach with Python
Greg Hogg - Updated 3Sum - Two pointers technique
Study Algorithms - 3Sum Detailed - Full solution with visuals
๐ Articles:
AlgoMonster - 3Sum Complete Guide - In-depth solution analysis
GeeksforGeeks - 3Sum Tutorial - Multiple approaches
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> threeSum(vector<int>& nums) {
/*Find all unique triplets that sum to zero*/
sort(nums.begin(), nums.end());
vector<vector<int>> result;
for (int i = 0; i < nums.size() - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue; // skip duplicates
int left = i + 1, right = nums.size() - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.push_back({nums[i], nums[left], nums[right]});
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
}
else if (sum < 0) {
left++;
}
else {
right--;
}
}
}
return result;
}
4. Container With Most Water
๐ Problem Link: LeetCode #11
๐ฅ Video Solutions:
NeetCode - Container With Most Water - Clear explanation with visuals
Greg Hogg - Container Water 2 Pointers - Python solution
Geekific - Detailed Explanation - Java implementation
๐ Articles:
AlgoMonster - Container With Most Water - Complete guide with intuition
LeetCode Official Solution - Multiple approaches
#include <vector>
#include <algorithm>
using namespace std;
int maxArea(vector<int>& height) {
/*Find container that holds most water*/
int left = 0, right = height.size() - 1;
int max_water = 0;
while (left < right) {
int width = right - left;
int current_water = width * min(height[left], height[right]);
max_water = max(max_water, current_water);
if (height[left] < height[right]) {
left++;
} else {
right--;
}
}
return max_water;
}
๐ด Hard Problems
5. Trapping Rain Water
๐ Problem Link: LeetCode #42
๐ฅ Video Solutions:
NeetCode - Trapping Rain Water - Multiple approaches explained
Greg Hogg - Trapping Rain Water 2 Pointers - Optimal solution
NeetCode Solutions - Written explanation
๐ Articles:
AlgoMonster - Trapping Rain Water - Detailed solution breakdown
GeeksforGeeks - Trapping Rain Water - Multiple approaches with illustrations
#include <vector>
#include <algorithm>
using namespace std;
int trap(vector<int>& height) {
/*Calculate trapped rainwater*/
int left = 0, right = height.size() - 1;
int left_max = 0, right_max = 0, water = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= left_max) {
left_max = height[left];
} else {
water += left_max - height[left];
}
left++;
} else {
if (height[right] >= right_max) {
right_max = height[right];
} else {
water += right_max - height[right];
}
right--;
}
}
return water;
}
When to Use Two Pointers Pattern
โ Perfect Scenarios
Array or string is sorted
Need to find pairs/triplets with specific sum
Looking for palindromes
Removing duplicates in-place
Partitioning arrays
Problems asking for O(1) space solution
๐ซ Not Suitable When
Array is unsorted (unless sorting first is acceptable)
Need to track multiple elements simultaneously
Problem requires complex state management
Dynamic programming is more appropriate
Practice Schedule: Your Two Pointers Mastery Plan
๐ Day 2-3: Foundation
Two Sum II - Master the basics
Valid Palindrome - String manipulation
Move Zeroes - Array modification
๐ Day 4-5: Intermediate
Remove Duplicates - In-place modification
3Sum - Triple pointer technique
Container With Most Water - Optimization
๐ Day 6-7: Advanced
Trapping Rain Water - Complex logic
4Sum - Extension to multiple pointers
Sort Colors - Dutch National Flag
Essential Resources for Two Pointers
๐ฅ Video Learning Playlists
NeetCode Two Pointers Playlist - Complete visual explanations
Striver Two Pointers Playlist - Language independent course
Solving All Two Pointer Problems - Blind75 problems solved
๐ Practice Platforms
LeetCode Two Pointers Tag - 210+ problems
NeetCode.io Two Pointers - Curated Blind75 list
AlgoMonster Two Pointers - Pattern-focused learning
๐ Comprehensive Guides
GeeksforGeeks Two Pointers - Complete tutorial with examples
TakeUForward Two Pointers - Detailed explanation with code
USACO Guide Two Pointers - Competitive programming perspective
๐ Interactive Learning
LeetCode Two Pointers Tutorial - Interactive course
InterviewBit Two Pointers - Practice with hints
Interviewing.io Two Pointers - Real interview questions
Interview Tips: Ace Two Pointers Questions
๐ฏ Problem-Solving Framework
Identify the pattern: Does it involve pairs/comparisons?
Check constraints: Is array sorted? Can we modify in-place?
Choose pointer type: Opposite direction vs same direction
Handle edge cases: Empty array, single element, no solution
Optimize: Can we reduce time/space complexity?
๐ฌ Interview Communication
Explain your approach: "I'll use two pointers starting from opposite ends"
Discuss time complexity: "This reduces from O(nยฒ) to O(n)"
Handle edge cases: "Let me check what happens with empty input"
Walk through examples: Show your solution step-by-step
๐จ Common Pitfalls to Avoid
Infinite loops: Ensure pointers always move toward each other
Index out of bounds: Check boundaries before accessing elements
Missing edge cases: Empty arrays, single elements, no valid pairs
Duplicate handling: In problems like 3Sum, skip duplicate values
Key Takeaways
๐ฏ Master These Concepts
Two pointers reduces O(nยฒ) to O(n) for many array problems
Three main types: opposite direction, same direction, sliding window
Perfect for sorted arrays and palindrome problems
Space efficient: Usually O(1) space complexity
๐ Next Steps
Practice daily: Solve 2-3 two pointers problems
Time yourself: Aim for 15-20 minutes per medium problem
Code without IDE: Practice on paper or whiteboard
Explain your solution: Teach the concept to someone else
Tomorrow's Preview: Sliding Window Pattern
Tomorrow, we'll explore the Sliding Window pattern - another fundamental technique that's perfect for:
Substring problems
Maximum/minimum subarray problems
String pattern matching
Fixed-size window optimizations
๐ฎ Coming Up: Sliding Window Problems
Longest Substring Without Repeating Characters
Minimum Window Substring
Sliding Window Maximum
Find All Anagrams in a String
Your Action Items
โ Today's Tasks
Solve the 3 foundation problems (Two Sum II, Valid Palindrome, Move Zeroes)
Implement solutions in C++
Watch recommended YouTube videos for visual understanding
Read articles from GeeksforGeeks and AlgoMonster for deeper insights
๐ Self-Assessment Questions
Can you explain when to use two pointers vs brute force?
What are the three types of two pointer techniques?
How do you handle duplicates in 3Sum problem?
What's the time complexity improvement of two pointers?
๐ Success Metric
By the end of today, you should be able to identify two pointers problems instantly and implement solutions confidently. Remember: Understanding the pattern is more important than memorizing individual solutions.
Keep practicing, stay consistent, and tomorrow we'll add another powerful pattern to your toolkit! ๐ช
๐ข Engage with the Community
Share your solutions and improvements in the comments
Ask questions if you're stuck on any problem
Help others who are learning alongside you
Happy Coding! ๐
Subscribe to my newsletter
Read articles from Aditya Kulkarni directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
