What this topic covers
29 subtopics- Two pointers5
- 2D arrays3
- Prefix sums3
- C strings2
- Character codes2
- Common bugs2
- Indexing2
- Kadane's algorithm2
- Palindromes2
- Rotation2
- Sliding window2
- Anagrams1
Show all 29 subtopics
- Bit tricks1
- Counting characters1
- Equality1
- Hashing1
- Immutability1
- Initialisation1
- Intervals1
- KMP1
- Memory layout1
- Operations and cost1
- Permutations1
- Prefix products1
- Reversal1
- Searching1
- String matching1
- Voting algorithm1
- Word manipulation1
- Beginner 15
- Intermediate 15
- Advanced 15
About this topic
Arrays and strings are the first round of almost every coding interview. Most questions reduce to a handful of patterns: prefix sums for range queries, two pointers on sorted data, a sliding window for subarrays, a hash map to remember what you have seen, and Kadane for maximum subarrays. Watch the language traps too – Java strings are immutable, == compares references, and a Python list multiplied by 3 copies references, not rows. Every output on this page comes from running the code.
Free preview
Sample questions
Try each one first, then open the answer for the explanation and why the other options are wrong.
Using the array shown, what is the value of a[a[1]]?
- 03
- 10
- 24
- 31
- 42
The answer is a number – work it out, then open the solution.
Show answer and explanation
Explanation
Work from the inside out: a[1] is 0, so a[a[1]] is a[0], which is 3. Indices start at 0.
What is the prefix-sum array p of this array, where p[i] = a[0] + … + a[i]?
- 03
- 11
- 24
- 31
- 45
- 3
- 1
- 4
- 1
- 5
- 3
- 4
- 5
- 5
- 6
- 14
- 11
- 10
- 6
- 5
- 3
- 4
- 8
- 9
- 14
Show answer and explanation
Explanation
Each entry adds the next element to the previous total: 3, 3 + 1, 4 + 4, 8 + 1, 9 + 5. With a prefix array, any range sum is one subtraction.
Why the other options are wrong
- AThat is the original array.
- BEach entry adds the running total, not just the previous element.
- CThose are suffix sums.
What is the largest sum of a contiguous (non-empty) subarray?
- 0-2
- 11
- 2-3
- 34
- 4-1
- 52
- 61
- 7-5
- 84
The answer is a number – work it out, then open the solution.
Show answer and explanation
Explanation
The best subarray is [4, −1, 2, 1] = 6. Kadane's algorithm finds it in one pass: at each element, either extend the current run or start a new one there – whichever is larger – and remember the best run seen.
The array gives bar heights of width 1. How many units of rain water are trapped between the bars?
- 00
- 11
- 20
- 32
- 41
- 50
- 61
- 73
- 82
- 91
- 102
- 111
The answer is a number – work it out, then open the solution.
Show answer and explanation
Explanation
Water above bar i is min(highest bar on its left, highest on its right) − h[i]. Summing over all bars gives 1 + 1 + 2 + 1 + 1 = 6. The two-pointer version computes this in O(n) time and O(1) space.