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

Aditya KulkarniAditya Kulkarni
10 min read

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

  1. Time Complexities:

    • Access: O(1)

    • Search: O(n)

    • Insertion: O(n)

    • Deletion: O(n)

  2. Space Complexity: O(1) for in-place operations, O(n) for additional arrays

  3. 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:

๐Ÿ“š Articles:

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:

๐Ÿ“š Articles:

#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:

๐Ÿ“š Articles:

#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:

๐Ÿ“š Articles:

#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:

๐Ÿ“š Articles:

#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:

๐Ÿ“š Articles:

#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

  1. Two Sum II - Master the basics

  2. Valid Palindrome - String manipulation

  3. Move Zeroes - Array modification

๐Ÿ“… Day 4-5: Intermediate

  1. Remove Duplicates - In-place modification

  2. 3Sum - Triple pointer technique

  3. Container With Most Water - Optimization

๐Ÿ“… Day 6-7: Advanced

  1. Trapping Rain Water - Complex logic

  2. 4Sum - Extension to multiple pointers

  3. Sort Colors - Dutch National Flag

Essential Resources for Two Pointers

๐ŸŽฅ Video Learning Playlists

๐Ÿ“š Practice Platforms

๐Ÿ“– Comprehensive Guides

๐Ÿ” Interactive Learning

Interview Tips: Ace Two Pointers Questions

๐ŸŽฏ Problem-Solving Framework

  1. Identify the pattern: Does it involve pairs/comparisons?

  2. Check constraints: Is array sorted? Can we modify in-place?

  3. Choose pointer type: Opposite direction vs same direction

  4. Handle edge cases: Empty array, single element, no solution

  5. 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

  1. Practice daily: Solve 2-3 two pointers problems

  2. Time yourself: Aim for 15-20 minutes per medium problem

  3. Code without IDE: Practice on paper or whiteboard

  4. 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

  1. Solve the 3 foundation problems (Two Sum II, Valid Palindrome, Move Zeroes)

  2. Implement solutions in C++

  3. Watch recommended YouTube videos for visual understanding

  4. 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! ๐Ÿš€


5
Subscribe to my newsletter

Read articles from Aditya Kulkarni directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aditya Kulkarni
Aditya Kulkarni