Array and string questions in coding rounds look endless, but most are a few patterns wearing different names. The hard part is often not writing Java syntax. It is recognising whether the problem wants two pointers, a sliding window, prefix sums, or frequency hashing before you start coding.
The array and string pattern map
Start by matching the wording and constraints to one of these four tools.
Pattern | Signal in the question | State you maintain |
|---|---|---|
Two pointers | Sorted input, pair or triplet, in-place reversal | Two indices moving towards or away from each other |
Sliding window | Longest or shortest contiguous range under a condition | A |
Prefix sums | Repeated range sums, subarray sum equals | Cumulative sum, often with a frequency map |
Frequency hashing | Anagrams, duplicates, character counts, first unique |
|
The patterns can combine. A sliding window may use a frequency map, and a prefix-sum solution may use a HashMap. The name tells you how the search moves; the data structure tells you what information it remembers.
If you are preparing broadly, the DSA interview questions for placements show how these patterns sit beside recursion, trees, graphs and dynamic programming.
Java String facts that affect the solution
String is immutable. An operation does not edit the existing object; it creates or returns another string. Repeated concatenation can therefore hide expensive copying:
String result = "";
for (char c : chars) {
result += c;
}As result grows, each concatenation copies the characters accumulated so far. Across n iterations, the total work can become O(n²). Use StringBuilder when building a result incrementally:
StringBuilder result = new StringBuilder();
for (char c : chars) {
result.append(c);
}
String answer = result.toString();For lowercase English letters, s.charAt(i) - 'a' maps a character to an index from 0 to 25. That makes int[26] a compact alternative to a map. Use it only when the character set really is limited that way.
Also remember that s.substring(i, j) creates a string containing indices i through j - 1, and copying that range costs O(length). Creating substrings repeatedly inside a loop can turn a clean-looking solution into a slower one. The string pool that immutability makes possible, and the == versus equals() trap that pool creates, are worked through in String handling in Java: string pool, immutability and fresher-test questions.
Worked sliding window: longest substring without repeats
Take s = "abcabcbb". We need the length of the longest substring containing no repeated character. The answer is 3, from windows such as "abc", "bca", and "cab".
Maintain:
left, the start of the current valid window.right, the index currently being processed.lastIndex, a map from each character to its most recent index.maxLen, the best valid-window length seen so far.
When the current character was last seen at an index greater than or equal to left, move left to one position after that old index. Using Math.max prevents left from moving backwards.
static int longestUniqueSubstring(String s) {
Map<Character, Integer> lastIndex = new HashMap<>();
int left = 0;
int maxLen = 0;
for (int right = 0; right < s.length(); right++) {
char ch = s.charAt(right);
if (lastIndex.containsKey(ch)) {
left = Math.max(left, lastIndex.get(ch) + 1);
}
lastIndex.put(ch, right);
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}Now trace every step:
| Character | Action | Valid window |
|
|---|---|---|---|---|
0 |
| New character |
| 1 |
1 |
| New character |
| 2 |
2 |
| New character |
| 3 |
3 |
| Last |
| 3 |
4 |
| Last |
| 3 |
5 |
| Last |
| 3 |
6 |
| Last |
| 3 |
7 |
| Last |
| 3 |
At right = 2, the length is 2 - 0 + 1 = 3. Later valid windows reach the same length but never exceed it, so the final answer is maxLen = 3.

Each index enters the right edge once, and left only moves forward. The method takes O(n) time and O(min(n, charset)) extra space.
The other three patterns with concrete inputs
Two pointers on a sorted array
For arr = [1, 3, 5, 8] and target 8, begin with left = 0 and right = 3. The sum 1 + 8 = 9 overshoots, so decrease right to 2. Now 1 + 5 = 6 falls short, so increase left to 1. Then 3 + 5 = 8 matches, and the pair sits at indices (1, 2). Three comparisons settle a question that brute force answers in O(n²).
The rule is symmetric: too small means increase left for a larger value, too large means decrease right for a smaller one. Sorting is what licenses those moves. On an unsorted array neither direction is justified, and the scan collapses back to checking every pair.
Prefix sum with a frequency map
To count subarrays whose sum is k, keep a running prefix sum. At each position, a previous prefix equal to prefix - k marks a subarray summing to k, because prefix - previousPrefix = k. Store how often each prefix has appeared, including an initial frequency of one for prefix zero.
Take arr = [1, 2, 3, -3, 1] with k = 3. Start the frequency map at {0: 1} and read left to right, looking up prefix - k before recording the new prefix.
|
|
|
| Times seen already | Running count |
|---|---|---|---|---|---|
|
|
|
| 0 | 0 |
|
|
|
| 1 | 1 |
|
|
|
| 1 | 2 |
|
|
|
| 1 | 3 |
|
|
|
| 1 | 4 |
The count ends at 4, and the four subarrays are [1, 2], [3], [1, 2, 3, -3] and [2, 3, -3, 1]. Each sums to 3, and the single pass found all four without ever re-adding a range.
Use long for the running sum when array values or lengths can make int overflow.
Frequency arrays for anagrams
To compare "listen" and "silent", create an int[26]. Increment for every letter in the first word and decrement for every letter in the second. Every final count is zero, so they are anagrams. This is O(n) time and O(1) extra space for a fixed 26-letter alphabet.
Complexity and implementation traps
Repeated
String +=in a loop can produce O(n²) copying. PreferStringBuilder.A copied
substringinside a loop adds work proportional to the extracted length.An
intrunning sum can overflow even when every individual element fits inint.The inclusive window length is
right - left + 1, notright - left.Changing array elements while the iteration logic depends on their old values can invalidate the solution's assumptions.
A frequency array is correct only when its alphabet and index mapping cover every possible input character.
Coding rounds reward a solution you can explain. State the invariant, such as “the current window has no repeated characters,” and then justify why each pointer move preserves it.
The short version and your next step
Two pointers, sliding windows, prefix sums, and frequency hashing cover a large share of array and string rounds. The abcabcbb trace is the reusable model: maintain a valid range, update only the necessary state, and never move left backwards.
Practise the patterns in the DSA using Java course and the Mera Placement Hoga bundle. The question bank carries about 1,500 Data Structure questions, including a dedicated array set. You can also browse the Coding and DSA courses for the rest of the placement-coding line-up.




