Array Operations

Loading concept...

🎒 Array Mastery: Your Adventure Through Array Operations

Imagine you have a magic backpack with numbered pockets. Each pocket holds one thing. That’s an array!


🏠 Arrays Fundamentals: Your Organized Toy Shelf

Think of an array like a toy shelf with numbered compartments. Each compartment (called an index) holds exactly one toy (a value).

What Makes Arrays Special?

int[] toys = {10, 20, 30, 40, 50};
//  Index:    0   1   2   3   4

Key Facts:

  • Index starts at 0 (not 1!)
  • Fixed size - once you build the shelf, you can’t add more compartments
  • Same type - all compartments hold the same kind of item

Quick Example

int[] numbers = new int[5];
// Creates 5 empty slots
numbers[0] = 100;
// Put 100 in first slot
System.out.println(numbers[0]);
// Prints: 100

Why Use Arrays?

  • Fast access: Jump directly to any pocket!
  • Organized storage: Everything has its place
  • Memory efficient: Items sit next to each other

🚶 Array Traversal and Manipulation: Walking Through Your Toys

Traversal = Visiting every toy on the shelf, one by one.

Think of it like checking each pocket in your backpack. You start at pocket 0, look inside, then move to pocket 1, and so on.

Two Ways to Walk Through

Method 1: Traditional For Loop

int[] nums = {5, 10, 15, 20};

for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}
// Prints: 5, 10, 15, 20

Method 2: Enhanced For Loop

for (int num : nums) {
    System.out.println(num);
}
// Same output, cleaner code!

Manipulation: Changing Your Toys

// Double every number
for (int i = 0; i < nums.length; i++) {
    nums[i] = nums[i] * 2;
}
// Array becomes: {10, 20, 30, 40}

📊 Prefix Sum Arrays: Running Totals Magic

Story Time: Imagine you’re counting your allowance each week. A prefix sum tells you “How much money do I have in TOTAL up to this week?”

The Magic Formula

prefixSum[i] = sum of all elements from index 0 to i

Building a Prefix Sum

int[] money = {5, 3, 7, 2};
int[] total = new int[4];

total[0] = money[0];  // 5
for (int i = 1; i < 4; i++) {
    total[i] = total[i-1] + money[i];
}
// total = {5, 8, 15, 17}

Why Is This Magical?

Question: “What’s the sum from index 1 to index 3?”

Without prefix sum: Add 3 + 7 + 2 = 12 (slow!)

With prefix sum: total[3] - total[0] = 17 - 5 = 12 (instant!)

graph TD A[Original: 5, 3, 7, 2] --> B[Prefix: 5, 8, 15, 17] B --> C[Range Sum = prefix_right - prefix_left-1]

🔄 Difference Arrays: The Undo Button

Story: Your teacher wants to give +10 bonus points to students 2 through 5. Then +5 to students 3 through 7. How do you track all changes efficiently?

Difference Array = Records changes at boundaries instead of updating every single element.

The Clever Trick

Instead of:

scores[2] += 10
scores[3] += 10
scores[4] += 10
scores[5] += 10  // Slow!

Do this:

int[] diff = new int[n + 1];
// Add 10 from index 2 to 5
diff[2] += 10;   // Start adding here
diff[6] -= 10;   // Stop adding here

Rebuild the Original

int[] result = new int[n];
result[0] = diff[0];
for (int i = 1; i < n; i++) {
    result[i] = result[i-1] + diff[i];
}

Power Move: Many range updates become O(1) each!


✖️ Product of Array Except Self

Puzzle: For each position, find the product of ALL OTHER numbers (without using division!).

Input: [1, 2, 3, 4] Output: [24, 12, 8, 6]

  • Index 0: 2 × 3 × 4 = 24
  • Index 1: 1 × 3 × 4 = 12
  • And so on…

The Two-Pass Trick

int[] nums = {1, 2, 3, 4};
int[] result = new int[4];

// Pass 1: Products from LEFT
int left = 1;
for (int i = 0; i < 4; i++) {
    result[i] = left;
    left *= nums[i];
}
// result = {1, 1, 2, 6}

// Pass 2: Multiply by products from RIGHT
int right = 1;
for (int i = 3; i >= 0; i--) {
    result[i] *= right;
    right *= nums[i];
}
// result = {24, 12, 8, 6}

Why No Division? What if there’s a zero? Division breaks!


🏆 Kadane’s Algorithm: Finding Treasure

The Quest: Find the group of consecutive numbers with the biggest sum.

Story: Imagine walking on a number line. Some spots give you coins (+), some take coins (-). Find the best stretch to walk!

The Brilliant Idea

At each step, ask: “Should I keep adding to my current streak, or start fresh here?”

int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};

int currentSum = nums[0];
int maxSum = nums[0];

for (int i = 1; i < nums.length; i++) {
    // Fresh start OR continue?
    currentSum = Math.max(nums[i],
                          currentSum + nums[i]);
    maxSum = Math.max(maxSum, currentSum);
}
// maxSum = 6 (from [4, -1, 2, 1])

Visual Journey

graph TD A[-2] -->|Start: -2| B[1] B -->|Reset to 1| C[-3] C -->|1-3=-2| D[4] D -->|Reset to 4| E[-1] E -->|4-1=3| F[2] F -->|3+2=5| G[1] G -->|5+1=6 MAX!| H[-5]

📈 Maximum Subarray Sum

This is exactly what Kadane’s Algorithm solves! Let’s see one more example:

Array: [5, -9, 6, -2, 3]

Index Value Current Sum Max So Far
0 5 5 5
1 -9 -4 5
2 6 6 (reset!) 6
3 -2 4 6
4 3 7 7

Answer: Maximum sum is 7 from subarray [6, -2, 3]


🎢 Maximum Product Subarray

Twist: Now we multiply instead of add! But watch out for negatives…

Key Insight: A negative times a negative = positive! So we track BOTH the minimum AND maximum.

The Strategy

int[] nums = {2, 3, -2, 4};

int maxProd = nums[0];
int minProd = nums[0];  // Track this too!
int result = nums[0];

for (int i = 1; i < nums.length; i++) {
    int temp = maxProd;

    maxProd = Math.max(nums[i],
        Math.max(maxProd * nums[i],
                 minProd * nums[i]));

    minProd = Math.min(nums[i],
        Math.min(temp * nums[i],
                 minProd * nums[i]));

    result = Math.max(result, maxProd);
}
// result = 6 (from [2, 3])

Why Track Minimum?

  • Array: [-2, 3, -4]
  • -2 × 3 = -6 (bad)
  • -6 × -4 = 24 (amazing!)

The minimum became the maximum!


🗺️ Your Array Operations Map

graph LR A[Array Operations] --> B[Basics] A --> C[Running Calculations] A --> D[Optimization Problems] B --> B1[Traversal] B --> B2[Manipulation] C --> C1[Prefix Sum] C --> C2[Difference Array] C --> C3[Product Except Self] D --> D1[Kadane's Algorithm] D --> D2[Max Subarray Sum] D --> D3[Max Product Subarray]

🌟 Quick Reference

Technique Use When Time
Prefix Sum Range sum queries O(1) query
Difference Array Range updates O(1) update
Product Except Self Avoid division O(n)
Kadane’s Max sum subarray O(n)
Max Product Handle negatives O(n)

🎯 Remember This!

  1. Arrays start at index 0 - Always!
  2. Prefix sum - Precompute for fast range queries
  3. Difference array - Mark boundaries, not every element
  4. Kadane’s choice - “Continue or restart?”
  5. Products with negatives - Track min AND max

You’ve got this! Arrays are your organized friends waiting to be explored! 🚀

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.