Stop 10 · Data Structures & Algorithms in JavaTopics · 2/11

Array & String Problems

Part of the Java Roadmap

In short

The first question in most coding rounds is about an array or a string. A handful of patterns, like prefix sums and frequency counting, crack a surprising number of them.

Most coding rounds start with array and string problems: prefix sums, two pointers, sliding window, frequency counting and in-place modification.

The jaadu leans on a roadside milestone by a highway, looking back at an earlier milestone in the distance and counting on its fingers.

Think of it like this

Milestones on the highway

Driving from Mumbai to Pune, you don't measure the distance between two towns with a tape. You read the milestones: stone at km 120 minus stone at km 75 gives 45 km. A prefix sum array is a row of milestones, so any stretch is just one subtraction.

Watch it happen

Prefix sums of daily sales

3
0
1
1
4
2
1
3
5
4

1/4Units sold over five days. We want fast answers to 'how many sold from day i to day j?'.

The big ideas

What you need to know

Prefix sums

One O(n) pass lets you answer any range-sum question in O(1). Great for subarray sum problems.

Frequency counting

An int[26] for lowercase letters, or a HashMap<Character, Integer> for anything, solves anagram and first-unique problems.

Strings are immutable

s += c in a loop creates a new String each time, which is O(n²). Use StringBuilder and call toString() once.

equals, not ==

Compare string contents with equals(). == checks whether two variables point to the same object.

See it in code

Walk through the code

java
1import java.util.HashMap;2import java.util.Map;3 4public class ArrayStringProblems {5    // Prefix sums: answer any range-sum query in O(1)6    static int[] prefixSums(int[] nums) {7        int[] prefix = new int[nums.length + 1];8        for (int i = 0; i < nums.length; i++) {9            prefix[i + 1] = prefix[i] + nums[i];10        }11        return prefix;12    }13 14    // Frequency counting: are two lowercase words anagrams?15    static boolean isAnagram(String a, String b) {16        if (a.length() != b.length()) return false;17        int[] count = new int[26];18        for (int i = 0; i < a.length(); i++) {19            count[a.charAt(i) - 'a']++;20            count[b.charAt(i) - 'a']--;21        }22        for (int c : count) if (c != 0) return false;23        return true;24    }25 26    // HashMap: first character that appears only once27    static char firstUnique(String s) {28        Map<Character, Integer> freq = new HashMap<>();29        for (char c : s.toCharArray()) freq.merge(c, 1, Integer::sum);30        for (char c : s.toCharArray()) if (freq.get(c) == 1) return c;31        return '_';32    }33}

1/4prefix has one extra slot so prefix[0] = 0 and the range formula needs no special case.

Three classic patterns. isAnagram("listen", "silent") is true and firstUnique("bharat") is 'b'.

Save yourself the pain

Common mistakes

Oops

Building a result with result += ch inside a loop.

Do this instead

Use StringBuilder sb = new StringBuilder(); sb.append(ch); then sb.toString() at the end.

Oops

Looping with i <= arr.length.

Do this instead

Valid indexes are 0 to length - 1. The extra step throws ArrayIndexOutOfBoundsException.

Oops

if (word == "java")

Do this instead

Use "java".equals(word). It compares contents and is safe even when word is null.

Your mission

Five warm-up problems

~60 min

Quick check

Why is count[ch - 'a'] a valid index for lowercase letters?

Go deeper

  1. 1Solve 10 easy array and string problems on LeetCode.
  2. 2Learn the two pointers and sliding window patterns.
  3. 3Use char arrays or int[26] counters for fast character counting.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge