Arrays and Strings Problems
# 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.
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]
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 executestring += "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).
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.7. Real-World Scenario: The Subarray Sum
*Prompt:* Find if there is a continuous subarray that adds up to a targetK.
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 functionisAnagram(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 usei < len(arr).
-
Modifying an Array while iterating over it: Trying to
arr.remove(element)inside aforloop 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. Write a function to reverse an array in-place (O(1) extra space).
-
2.
Trace the Prefix Sum array for the input
[2, 4, 6, 8].
12. MCQs
Why is accessing an array element by its index arr[5] considered an O(1) Constant Time operation?
Why is inserting an element at the *beginning* of an Array an O(N) operation?
What is the fundamental concept behind the "Prefix Sum" pattern?
Using a Prefix Sum array P, what is the formula to find the sum of elements between index L and index R?
Why is using string concatenation (string += "a") inside a loop considered a massive anti-pattern in Java and Python?
What is the optimal Time and Space complexity to check if two strings are valid Anagrams?
When checking if a string is a Palindrome (reads the same forwards and backwards), what is the standard algorithmic approach?
What is the most common cause of an "Index Out of Bounds" error when traversing an array?
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?
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 arrayoutputsuch thatoutput[i]is equal to the product of all the elements ofnumsexceptnums[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?
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).