rohithtp-cv

Prefix Sum

A Prefix Sum (also known as a cumulative sum) is a powerful technique used to pre-process an array so that the sum of any subarray (a range of elements) can be calculated in constant time, $O(1)$.

Essentially, you create a new array where each element at index $i$ stores the sum of all elements from the original array starting from the beginning up to index $i$.


1. The Logic

If you have an array $A$ of size $n$, the prefix sum array $P$ is defined as:
$P[i] = A[0] + A[1] + \dots + A[i]$

Or, more efficiently through recurrence:


2. Example Walkthrough

Let’s take a sample array and build its prefix sum.

Index 0 1 2 3 4
Array A 3 1 4 1 5
Prefix Sum P 3 4 8 9 14

Calculations:


3. Why Use It? (Range Sum Queries)

The primary advantage is calculating the sum of elements between two indices $L$ and $R$ ($sum(L, R)$).

Instead of looping through the array every time—which takes $O(N)$—you can use the formula:
$\text{Sum}(L, R) = P[R] - P[L-1]$
(Note: If L=0, the sum is simply* *P[R]).

Example: Find the sum of elements from index 2 to 4 in the array above.


4. Complexity Analysis


5. Implementations

def build_prefix_sum(arr):
    n = len(arr)
    prefix_sum = [0] * n
    prefix_sum[0] = arr[0]
    
    for i in range(1, n):
        prefix_sum[i] = prefix_sum[i-1] + arr[i]
        
    return prefix_sum

# Usage
data = [3, 1, 4, 1, 5]
p_sum = build_prefix_sum(data) # [3, 4, 8, 9, 14]
public class PrefixSum {
    public static int[] buildPrefixSum(int[] arr) {
        int n = arr.length;
        if (n == 0) return new int[0];

        int[] prefixSum = new int[n];
        prefixSum[0] = arr[0];

        for (int i = 1; i < n; i++) {
            prefixSum[i] = prefixSum[i - 1] + arr[i];
        }
        return prefixSum;
    }

    // Usage example
    public static void main(String[] args) {
        int[] data = {3, 1, 4, 1, 5};
        int[] pSum = buildPrefixSum(data); // [3, 4, 8, 9, 14]
        for (int v : pSum) {
            System.out.print(v + " ");
        }
    }
}

Two Pointer Technique

The Two Pointer Technique is one of the most efficient ways to search for pairs or subsegments in a linear data structure (like an array or linked list). It typically reduces a nested loop $O(n^2)$ solution down to a linear $O(n)$ solution.

It works by using two indices (the “pointers”) that move through the data independently based on specific conditions.


1. Common Variations

A. Opposite Ends (The “Squeeze”)

This is used when the array is sorted. You place one pointer at the start (left) and one at the end (right).

B. Same Direction (The “Fast and Slow”)

Both pointers start at the same side but move at different speeds or intervals.

C. Sliding Window

A specific type of two-pointer technique where the distance between the two pointers represents a “window.”


2. Code Example: Two Sum (Sorted Array)

If you are given a sorted array, the two-pointer approach is more space-efficient ($O(1)$) than a Hash Map.

def two_sum_sorted(nums, target):
    left = 0
    right = len(nums) - 1
    
    while left < right:
        current_sum = nums[left] + nums[right]
        
        if current_sum == target:
            return [left, right]
        elif current_sum < target:
            left += 1  # Need a larger sum
        else:
            right -= 1 # Need a smaller sum
            
    return []

3. When to use Two Pointers?

You should reach for this tool if you see these keywords:


4. Complexity Analysis

Sliding Window (explained)

The Sliding Window technique is a specific variation of the Two-Pointer approach. It is primarily used to convert nested loops ($O(n^2)$) into a single pass ($O(n)$) when dealing with subarrays or substrings.

Instead of recalculating everything from scratch for every possible range, you “slide” a window across the data, adding one element at the front and removing one from the back.


1. The Two Types of Windows

A. Fixed-Size Window

The window size $k$ remains constant. You move the window by adding the next element and subtracting the element that is no longer in the range.

B. Variable-Size Window

The window grows or shrinks dynamically based on a condition (like a target sum or a count of unique characters).


2. Implementation (Python)

Here is a classic example: Maximum sum of a subarray of size $K$.

def max_sum_subarray(arr, k):
    n = len(arr)
    if n < k:
        return -1
    
    # Calculate sum of first window
    window_sum = sum(arr[:k])
    max_val = window_sum
    
    # Slide the window
    for i in range(n - k):
        # Subtract the element leaving, add the element entering
        window_sum = window_sum - arr[i] + arr[i + k]
        max_val = max(max_val, window_sum)
        
    return max_val

3. When to Use It

Look for these “green flags” in a problem description:


4. Complexity Comparison

Feature Brute Force Sliding Window
Time Complexity $O(n \times k)$ or $O(n^2)$ $O(n)$
Space Complexity $O(1)$ $O(1)$ (usually)

HashMap-based Problems for Arrays

HashMaps (or Dictionaries) are the “cheat code” of array problems. They allow you to trade a little bit of Space ($O(n)$) for a massive gain in Time ($O(1)$ lookup).

If you see a problem asking about frequencies, existence, or pairs, a HashMap is likely the answer. Here are the most essential problem patterns you’ll encounter.


1. Frequency Counting

The most basic use: counting how many times each element appears.


2. Existence & Complement (The “Two Sum” Pattern)

Checking if a value (or its “partner”) has been seen before.


3. Grouping & Categorization

Using a sorted version or a property of the data as the “Key.”


4. Subarray Sum Equals K (Prefix Sum + HashMap)

This is a high-level pattern that combines two techniques we’ve discussed.


5. Longest Consecutive Sequence

Finding the length of the longest sequence of integers (e.g., [1, 2, 3, 4]) in an unsorted array.


Summary Table

Problem Type HashMap Key HashMap Value
Frequency Element Count
Two Sum Element Index
Anagrams Sorted String List of original strings
Subarray Sum Prefix Sum Occurrences
Longest Seq Element Boolean/Presence