Foundations · core
Arrays and strings
Most array and string problems are solved in one pass with a few running variables, a prefix sum, or in-place writes with a write pointer. Keep every call inside the loop O(1).
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- One pass with running state: best so far, count, last seen. Kadane: cur = max(x, cur + x); best = max(best, cur). It handles all-negative arrays if you start from the first element.
- Prefix sums: pre[i + 1] = pre[i] + a[i]; the sum of a[l..r] is pre[r + 1] - pre[l]. 'Count subarrays with sum k': for each prefix p, add how many times (p - k) was seen before, using a hash map of prefix counts that starts with {0: 1}.
- Write pointer for in-place work: read with i, write with w (remove duplicates, move zeros). O(1) extra space.
- Scan from the right when the answer depends on what comes after (leaders, next greater). A difference array turns many range updates into O(1) each (car pooling).
- Strings: index a count array of 26 with (character - 'a'); counting is O(n) while sorting the characters is O(n log n).
- Strings are immutable in Java and Python, so building one with + in a loop copies each time and is O(n²); use StringBuilder in Java and ''.join(list) in Python. In C++ std::string += appends in amortised O(1).
- Always test: empty input, one element, all equal, all negative, very long input (and the sum may need a 64-bit type).
The red pen
Common traps: mistake → fix
Mistake: Kadane starting with best = 0 is fine
Fix: it returns 0 for [-3, -1]; start with the first element.
Mistake: Removing from the middle of an array inside a loop is cheap
Fix: each removal is O(n), so the loop becomes O(n²).
Mistake: Sorting the characters is the only way to compare anagrams
Fix: a 26-count array is O(n) and simpler to defend.
Easy to hard
Questions interviewers ask, easy to hard
- Find the maximum subarray sum. What is the complexity?
- What if all numbers are negative?
- Now the array is circular (LeetCode 918). What changes?
- Count subarrays whose sum is k, with negative numbers allowed.
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.