DSA Mastering Series • Module 1

Mastering Arrays in DSA

Interactive workspace covering array memory layout, 8 core algorithm patterns, and live simulators.

Array Mastery0%
0 of 15 DoneLearner Hub

Core Algorithm Patterns

1. Two Pointers (Opposite Direction)

Initialize pointers at the start (left) and end (right) of a sorted array and move them inward based on condition.

Time: O(N)Space: O(1)
Key Intuition & Concept

Reduces O(N²) nested loops searching for pairs into O(N) by exploiting sorted property or symmetrical checks.

When to apply this pattern:

Array is sorted (or can be sorted)
Finding target pairs, triplets, or range boundaries
Validating palindromes or reversing elements in-place

Benchmark Code Templates & Explanations

Two Sum II - Input Array Is Sorted[LeetCode]

Given a 1-indexed sorted array, find two numbers that add up to a specific target number.

Solution Approach: Since the array is sorted, if left + right < target, we need a larger sum so left++. If left + right > target, we need a smaller sum so right--.
vector<int> twoSum(vector<int>& numbers, int target) {
    int left = 0, right = numbers.size() - 1;
    while (left < right) {
        int sum = numbers[left] + numbers[right];
        if (sum == target) return {left + 1, right + 1};
        else if (sum < target) left++;
        else right--;
    }
    return {};
}

Container With Most Water[LeetCode]

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Solution Approach: Area is limited by the shorter line: (right - left) * min(h[left], h[right]). Always move the shorter line inward, because keeping it can never yield a larger area.
int maxArea(vector<int>& height) {
    int left = 0, right = height.size() - 1;
    int maxW = 0;
    while (left < right) {
        int h = min(height[left], height[right]);
        maxW = max(maxW, h * (right - left));
        if (height[left] < height[right]) left++;
        else right--;
    }
    return maxW;
}