Skip to main content

Arrays, Strings, and Pattern Techniques · Linear Structures

Arrays

Arrays teach indexed access, fixed-size storage, traversal, mutation, and the importance of careful loop bounds.

Student Focus

We use arrays as the first laboratory for tracing, testing, and runtime analysis.

Guided Lesson Notes

Understanding Arrays

Arrays focuses on contiguous sequences, index movement, and the state that can be reused while scanning. Arrays teach indexed access, fixed-size storage, traversal, mutation, and the importance of careful loop bounds.

Model: picture the input as boxes with numbered positions; every algorithm decision should say which positions are being read, updated, skipped, or remembered.

Invariant: the variables beside the array must summarize exactly the part of the array that has already been processed.

Implementation: careful loops, boundary checks, and small helper variables for sums, counts, positions, or best answers.

Use Arrays when the problem asks about a subarray, substring, range, pair, frequency, or a condition over consecutive values.

Visual Model

A small picture for Arrays

i=0

4

i=1

1

i=2

7

i=3

2

i=4

5

i=5

9

i=6

3

i=7

6

Array and string techniques usually become clear when each index has a job: scan, compare, count, enter a range, leave a range, or store a best answer.

Key Ideas

  • Index-based access
  • Traversal and mutation
  • Boundary conditions

Practice Prompts

  • Implement max, sum, count, and rotate operations.
  • Find and fix three off-by-one errors in array loops.

Vocabulary

Terms students should be able to say clearly

Index

The numeric position used to access an item directly.

Window

A contiguous section of the array or string currently being considered.

Prefix

Information accumulated from the start of the sequence up to a position.

Boundary

The first or last valid position included in the current scan.

State

The running information kept while the loop moves.

Invariant

The rule that makes the running state trustworthy after each iteration.

Worked Example

Worked example: tracing Arrays

Trace a small input, focusing on index-based access.

  1. 1Write a small input where Arrays is clearly useful.
  2. 2Label the part of the input related to Index-based access.
  3. 3Perform one operation and explain which invariant is still true afterward.
  4. 4Run a second operation that touches an edge case, such as an empty side, duplicate value, boundary index, disconnected vertex, or tie.
  5. 5Finish by saying which operation dominates the runtime and why.

Complexity Check

Costs students should be able to explain

OperationTypical CostReason
Indexed accessO(1)Direct index lookup is fast when the position is known.
Full scanO(n)Most search, count, and validation tasks inspect each item once.
Middle insert/deleteO(n)Items often need to shift to keep order.

Common Mistakes

What to watch while practicing

  • Coding before drawing the structure or state changes.
  • Forgetting the invariant that makes the algorithm correct.
  • Testing only the sample input and skipping boundary cases.
  • Giving Big-O without explaining which operation dominates the work.

Interview-Style Coding Problem

Arrays interview problem: Maximum Product Subarray

Interview medium

Problem

Given an integer array that may contain negative values and zeros, find the maximum product of a non-empty contiguous subarray.

Input

The first line contains n. The second line contains n integers.

Output

Print the maximum product.

Sample Input

6
-2 3 -4 0 -1 -2

Sample Output

24

Why the sample works

The subarray -2, 3, -4 has product 24, which is the maximum.

Approach

  1. 1Track both the maximum and minimum product ending at the current index.
  2. 2A negative value can turn the minimum product into the new maximum product.
  3. 3Swap the two trackers when the current value is negative.
  4. 4Update the global best after processing each value.

O(n) time and O(1) extra space.

Java Solution

import java.util.*;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    long currentMax = sc.nextLong();
    long currentMin = currentMax;
    long answer = currentMax;

    for (int i = 1; i < n; i++) {
      long x = sc.nextLong();
      if (x < 0) {
        long temp = currentMax;
        currentMax = currentMin;
        currentMin = temp;
      }

      currentMax = Math.max(x, currentMax * x);
      currentMin = Math.min(x, currentMin * x);
      answer = Math.max(answer, currentMax);
    }

    System.out.println(answer);
  }
}

Python Solution

n = int(input())
a = list(map(int, input().split()))

current_max = a[0]
current_min = a[0]
answer = a[0]

for x in a[1:]:
    if x < 0:
        current_max, current_min = current_min, current_max

    current_max = max(x, current_max * x)
    current_min = min(x, current_min * x)
    answer = max(answer, current_max)

print(answer)

Practice Challenge

Make the idea your own

Create a two-minute explanation of Arrays: define it, trace one example, name one edge case, and give the runtime of the main operation.

Tutoring Connection

Need help with this topic?

Bring a question or code attempt to a tutoring session.