Arrays & Strings

beginner20 min

Arrays in Competitive Coding

Most contest problems start with an array or a string. The same few patterns—scanning, two indices, a fixed or growing window—cover a large share of easy and medium tasks.

Common Array Operations

// Traversal
for (int i = 0; i < arr.length; i++) {
    // Process arr[i]
}

// Enhanced for loop
for (int num : arr) {
    // Process num
}

// Two pointers technique
int left = 0, right = arr.length - 1;
while (left < right) {
    // Process arr[left] and arr[right]
    left++;
    right--;
}

// Sliding window
int windowSum = 0;
for (int i = 0; i < k; i++) {
    windowSum += arr[i];
}
for (int i = k; i < arr.length; i++) {
    windowSum = windowSum - arr[i-k] + arr[i];
    // Process windowSum
}

String Manipulation

Strings are essentially character arrays. Common operations include:

Length: str.length()

Character access: str.charAt(i)

Substring: str.substring(start, end)

Character array: str.toCharArray()

String building: StringBuilder

String Examples

Key Techniques

  • Two Pointers: For palindrome, two sum, container problems
  • Sliding Window: For substring, subarray problems
  • Prefix Sum: For range sum queries
  • Kadane’s Algorithm: For maximum subarray sum
  • Dutch National Flag: For array partitioning