Skip to main content
LeetCode Prep
CHAPTER 03 Beginner

Arrays and Strings Problems

Updated: May 18, 2026
5 min read

# CHAPTER 3

Arrays and Strings Problems

1. Chapter Introduction

Arrays and Strings form the absolute bedrock of coding interviews. Over 50% of the questions you face will involve manipulating these two contiguous data structures. Under the hood, a String is simply an Array of characters. This chapter covers essential traversal techniques, the highly tested "Prefix Sum" pattern, and fundamental string manipulations.

2. Arrays in Memory

An array is a collection of elements stored in contiguous (sequential) memory locations. Because the memory addresses are sequential, you can calculate the exact location of any element instantly using its index.
  • Accessing an element via index arr[i]: O(1) Time.
  • Searching for an element: O(N) Time.
  • Inserting/Deleting at the end: O(1) Time.
  • Inserting/Deleting at the beginning: O(N) Time (Because every subsequent element must be physically shifted over by one slot in memory).

3. Pattern 1: Array Traversal & Frequency Counting

The most basic pattern is looping through an array to count occurrences or find max/min values.

*LeetCode Example:* Majority Element (Find the element that appears > N/2 times). *Approach:* Use a Hash Map to count frequencies.

python
12345678
# Python implementation
def majorityElement(nums):
    countMap = {}
    for num in nums:
        countMap[num] = countMap.get(num, 0) + 1
        if countMap[num] > len(nums) // 2:
            return num
# Time: O(N), Space: O(N)
java
123456789
// Java implementation
public int majorityElement(int[] nums) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int num : nums) {
        map.put(num, map.getOrDefault(num, 0) + 1);
        if (map.get(num) > nums.length / 2) return num;
    }
    return -1;
}

4. Pattern 2: The Prefix Sum Array

This is a massive "cheat code" pattern for FAANG interviews. *The Problem:* You have an array [1, 2, 3, 4, 5]. You will receive 10,000 queries asking for the sum of elements between index L and index R. *Brute Force:* Run a for loop from L to R for every query. Time: O(N * Q). Too slow. *Optimized (Prefix Sum):* Create a new array where prefix[i] stores the sum of all elements from index 0 to i. Original: [1, 2, 3, 4, 5] Prefix: [1, 3, 6, 10, 15]

Now, the sum of any subarray from L to R can be calculated in O(1) Time using the formula: Sum(L, R) = prefix[R] - prefix[L - 1]

python
123456
def buildPrefixSum(nums):
    prefix = [0] * len(nums)
    prefix[0] = nums[0]
    for i in range(1, len(nums)):
        prefix[i] = prefix[i-1] + nums[i]
    return prefix

5. String Manipulation

Strings are Arrays of characters. The trickiest part about strings in technical interviews is understanding Immutability. In Python and Java, Strings cannot be changed. If you execute string += "a", it doesn't add "a" to the existing memory block; it allocates an entirely *new* memory block and copies the whole string over.

*Interview Rule:* If you need to build a string dynamically inside a loop, NEVER use string concatenation (+=).

  • In Java: Use StringBuilder.
  • In Python: Append characters to a List, then use "".join(list).

python
123456
# Python: Efficient String Building
def buildString(chars):
    res = []
    for c in chars:
        res.append(c) # O(1) List append
    return "".join(res) # O(N) Join

6. Pattern 3: Palindrome Checking

A palindrome reads the same forwards and backwards (e.g., "racecar"). *The Strategy:* Use two pointers (one at the start, one at the end) and move them towards the center.
javascript
123456789101112131415
// JavaScript implementation
function isPalindrome(s) {
    let left = 0;
    let right = s.length - 1;
    
    while (left < right) {
        if (s[left] !== s[right]) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}
// Time: O(N), Space: O(1)

7. Real-World Scenario: The Subarray Sum

*Prompt:* Find if there is a continuous subarray that adds up to a target K. This tests your knowledge of Prefix Sums combined with Hash Maps. By keeping a running sum (prefix sum) and checking if (current_sum - K) exists in a Hash Map of seen sums, you can solve this in O(N) time. This exact problem is asked constantly at Meta.

8. Mini Project: Build an Anagram Checker

Write a function isAnagram(s, t) that returns True if string t is an anagram of string s. *Solution 1 (Sorting):* Sort both strings and compare. Time: O(N log N). Space: O(1). *Solution 2 (Frequency Map):* Create an array of size 26 (for the alphabet). Increment counts for s, decrement for t. If the array is all zeroes, it's an anagram. Time: O(N). Space: O(1) (since array is always size 26).

9. Common Mistakes

  • Off-By-One Errors: In 0-indexed languages, looping to i <= len(arr) will cause an "Index Out of Bounds" error. Always use i < len(arr).
  • Modifying an Array while iterating over it: Trying to arr.remove(element) inside a for loop will shift all indices and cause massive bugs. Traverse backwards or use a new array.

10. Best Practices

  • Edge Cases First: Start every array problem by checking: if not nums or len(nums) == 0: return 0. Interviewers love candidates who handle edge cases defensively before writing core logic.

11. Exercises

  1. 1. Write a function to reverse an array in-place (O(1) extra space).
  1. 2. Trace the Prefix Sum array for the input [2, 4, 6, 8].

12. MCQs

Question 1

Why is accessing an array element by its index arr[5] considered an O(1) Constant Time operation?

Question 2

Why is inserting an element at the *beginning* of an Array an O(N) operation?

Question 3

What is the fundamental concept behind the "Prefix Sum" pattern?

Question 4

Using a Prefix Sum array P, what is the formula to find the sum of elements between index L and index R?

Question 5

Why is using string concatenation (string += "a") inside a loop considered a massive anti-pattern in Java and Python?

Question 6

What is the optimal Time and Space complexity to check if two strings are valid Anagrams?

Question 7

When checking if a string is a Palindrome (reads the same forwards and backwards), what is the standard algorithmic approach?

Question 8

What is the most common cause of an "Index Out of Bounds" error when traversing an array?

Question 9

If an interviewer asks you to find the "Majority Element" (appears > N/2 times) in an array, what data structure naturally counts the frequencies of elements in O(N) time?

Question 10

What is a critical "Best Practice" to perform before writing the core logic of any array problem?

14. Interview Questions

  • Q: "Given an array nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. You must write an algorithm that runs in O(n) time and without using the division operation." (LeetCode 238).

15. FAQs

  • Q: Are arrays and lists the same thing?
A: In Python, list acts like a dynamic array. In Java, int[] is a fixed-size array, while ArrayList<Integer> is dynamic (it resizes itself under the hood when it gets full).

16. Summary

Arrays and Strings rely on sequential memory. You must be deeply familiar with O(N) iteration, boundary conditions (preventing Index Out of Bounds), and edge cases (empty strings). The Prefix Sum pattern allows O(1) subarray calculations, while recognizing string immutability prevents accidental O(N^2) bottlenecks. Always remember: when frequencies or duplicates are involved, a Hash Map is usually the answer.

17. Next Chapter Recommendation

We hinted at Hash Maps in this chapter. In Chapter 4: Hash Maps and Sets, we will fully uncover the most powerful and frequently used data structure in the entire coding interview ecosystem.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·