Arrays and Strings in Java for Coding Rounds: The Core Patterns That Keep Coming Up

Stop treating every coding-round question as a new puzzle. Learn four reusable array and string patterns, then trace a sliding window on abcabcbb step by step.

KnowledgeGate Team

Exam prep & CS education

Updated 9 Aug 20266 min read

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 [left, right] range and a running summary

Prefix sums

Repeated range sums, subarray sum equals k

Cumulative sum, often with a frequency map

Frequency hashing

Anagrams, duplicates, character counts, first unique

HashMap or a fixed-size count array

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:

right

Character

Action

Valid window

maxLen

0

a

New character

a

1

1

b

New character

ab

2

2

c

New character

abc

3

3

a

Last a was 0, so left = 1

bca

3

4

b

Last b was 1, so left = 2

cab

3

5

c

Last c was 2, so left = 3

abc

3

6

b

Last b was 4, so left = 5

cb

3

7

b

Last b was 6, so left = 7

b

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.

Three snapshots of the sliding window over abcabcbb, at right = 2, 3 and 5, each showing the left and right bounds and the lastIndex map, with a final maxLen of 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.

i

arr[i]

prefix

prefix - k

Times seen already

Running count

0

1

1

-2

0

0

1

2

3

0

1

1

2

3

6

3

1

2

3

-3

3

0

1

3

4

1

4

1

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. Prefer StringBuilder.

  • A copied substring inside a loop adds work proportional to the extracted length.

  • An int running sum can overflow even when every individual element fits in int.

  • The inclusive window length is right - left + 1, not right - 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.