Java String Program · S60
Find All Anagram Indices in a String in Java
Slide a window as long as the pattern across the text and report every position where the window holds exactly the pattern's letters.
Problem Statement
Given strings s and p of lowercase letters, return every index of s where a substring that is an anagram of p begins, in increasing order.
Anagrams may overlap. If p is longer than s, the result is empty.
Input/Output Examples
s = "javajvaa", p = "ajv"Output[0, 2, 3, 4]Explanation: jav, vaj, ajv and jva all use a, j and v once.s = "abab", p = "ab"Output[0, 1, 2]Explanation: ab, ba and ab.s = "aaa", p = "b"Output[]Explanation: there is no b in s.Visual Explanation
The window at index 1 is "ava", which has two a's and no j, so it is rejected. Updating two counts per slide makes every check constant time.
Approaches
Both approaches check every window of length |p|. The first updates counts as it slides; the second sorts each window.
Approach 1: Sliding Window Counts (Recommended)
Idea: maintain the letter counts of the current window and compare them with the pattern's counts at every position.
- Count the pattern's letters in
need. - Add each new character to
window; once the window is too long, remove the character that leaves. - When the window is full and
windowequalsneed, record its start.
Time: O(n) · Space: O(1). Each comparison checks 26 counts, a constant.
Approach 2: Sort Each Window
Idea: sort the pattern once and every window of the same length, then compare the sorted arrays.
- Sort the pattern's characters.
- For each start, sort a copy of the window.
- Record the start if the arrays are equal.
Time: O(n × m log m) · Space: O(m).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Sliding Window Counts (Recommended)
The same window as in the permutation-in-string problem, but it keeps going and collects every match.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AnagramIndicesWindow {
// Fixed window of length |p| with letter counts; record each start where counts match
static List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
if (p.length() > s.length()) {
return result;
}
int[] need = new int[26];
int[] window = new int[26];
for (char c : p.toCharArray()) {
need[c - 'a']++;
}
for (int i = 0; i < s.length(); i++) {
window[s.charAt(i) - 'a']++;
if (i >= p.length()) {
window[s.charAt(i - p.length()) - 'a']--;
}
if (i >= p.length() - 1 && Arrays.equals(need, window)) {
result.add(i - p.length() + 1);
}
}
return result;
}
public static void main(String[] args) {
String[][] cases = {{"javajvaa", "ajv"}, {"abab", "ab"}, {"aaa", "b"}};
for (String[] c : cases) {
System.out.println("s=\"" + c[0] + "\", p=\"" + c[1] + "\" -> " + findAnagrams(c[0], c[1]));
}
}
}
s="javajvaa", p="ajv" -> [0, 2, 3, 4] s="abab", p="ab" -> [0, 1, 2] s="aaa", p="b" -> []
Time complexity: O(n) · Space complexity: O(1).
Approach 2: Sort Each Window
Simple and obviously correct, which makes it a good test oracle for the fast version.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AnagramIndicesSort {
// Sorts every window and compares it with the sorted pattern: O(n * m log m)
static List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
char[] target = p.toCharArray();
Arrays.sort(target);
for (int start = 0; start + p.length() <= s.length(); start++) {
char[] window = s.substring(start, start + p.length()).toCharArray();
Arrays.sort(window);
if (Arrays.equals(window, target)) {
result.add(start);
}
}
return result;
}
public static void main(String[] args) {
String[][] cases = {{"javajvaa", "ajv"}, {"abab", "ab"}, {"aaa", "b"}};
for (String[] c : cases) {
System.out.println("s=\"" + c[0] + "\", p=\"" + c[1] + "\" -> " + findAnagrams(c[0], c[1]));
}
}
}
s="javajvaa", p="ajv" -> [0, 2, 3, 4] s="abab", p="ab" -> [0, 1, 2] s="aaa", p="b" -> []
Time complexity: O(n × m log m) · Space complexity: O(m).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Sliding Window Counts | O(n) | O(1) |
| Sort Each Window | O(n × m log m) | O(m) |
Here n is the length of s and m the length of p. The sliding window does constant work per position; sorting each window costs O(m log m) per position.
Interview Tips and Recommended Approach
- Allow overlaps. Matches can start one position apart, as in
"abab". - Recognise the fixed window. Every anagram of
phas exactly|p|characters. - Optimise the comparison if asked. Track how many of the 26 counts currently match instead of comparing arrays.
- Return indexes, not substrings, unless the interviewer asks for the text.
Recommended Approach: Sliding Window Counts
Why: it scans the text once with two fixed-size arrays, and the update-two-counts pattern carries over to many other window problems.