Java String Program · S35
Permutation in String in Java
Does s contain some rearrangement of p as a contiguous block? Slide a window of length |p| across s and compare letter counts.
Problem Statement
Given two strings p and s, return true if some substring of s is a permutation (an anagram) of p.
Both strings contain only lowercase English letters. If p is longer than s, the answer is false.
Input/Output Examples
p = "ab", s = "xbay"OutputtrueExplanation: the substring "ba" is a rearrangement of "ab".p = "abc", s = "cbxab"OutputfalseExplanation: no window of length 3 has exactly one a, one b and one c.p = "ad", s = "dad"OutputtrueExplanation: the first window "da" already matches.Visual Explanation
"xbay": the first window "xb" has the wrong letters; the second window "ba" (purple) has exactly the letters of "ab".Moving the window one step adds one character on the right and removes one on the left, so the counts can be updated in constant time instead of being recounted.
Approaches
Both approaches compare letter counts. The first updates the counts as the window slides; the second recounts every window.
Approach 1: Sliding Window Counts (Recommended)
Idea: keep the letter counts of the current window and compare them with the counts of p after each slide.
- Count the letters of
pand of the first window ofs. - If the two arrays are equal, return
true. - Slide the window: add the entering character and remove the leaving one, then compare again.
Time: O(n) · Space: O(1). Each comparison checks 26 values, a constant.
Approach 2: Recount Each Window
Idea: for every start position, count p and the window from scratch in one array and check that all counts are zero.
- For each start, add 1 for each letter of
pand subtract 1 for each letter of the window. - If every count is 0, return
true. - Otherwise, move on to the next start.
Time: O(n × m) · Space: O(1).
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)
Arrays.equals() on two int[26] arrays is a fixed amount of work per step.
import java.util.Arrays;
public class PermutationWindow {
// Slides a window of length |p| over s and compares letter counts (lowercase a-z)
static boolean containsPermutation(String p, String s) {
if (p.length() > s.length()) {
return false;
}
int[] need = new int[26];
int[] window = new int[26];
for (int i = 0; i < p.length(); i++) {
need[p.charAt(i) - 'a']++;
window[s.charAt(i) - 'a']++;
}
if (Arrays.equals(need, window)) {
return true;
}
for (int i = p.length(); i < s.length(); i++) {
window[s.charAt(i) - 'a']++; // character entering the window
window[s.charAt(i - p.length()) - 'a']--; // character leaving the window
if (Arrays.equals(need, window)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
String[][] cases = {{"ab", "xbay"}, {"abc", "cbxab"}, {"ad", "dad"}, {"abcd", "abc"}};
for (String[] c : cases) {
System.out.println("p=\"" + c[0] + "\", s=\"" + c[1] + "\" -> " + containsPermutation(c[0], c[1]));
}
}
}
p="ab", s="xbay" -> true p="abc", s="cbxab" -> false p="ad", s="dad" -> true p="abcd", s="abc" -> false
Time complexity: O(n) · Space complexity: O(1).
Approach 2: Recount Each Window
Easier to get right, and a good first step before optimising to the sliding version.
public class PermutationRecount {
// Recounts every window from scratch: simpler, but O(n * m)
static boolean containsPermutation(String p, String s) {
for (int start = 0; start + p.length() <= s.length(); start++) {
int[] counts = new int[26];
for (int i = 0; i < p.length(); i++) {
counts[p.charAt(i) - 'a']++;
counts[s.charAt(start + i) - 'a']--;
}
boolean match = true;
for (int c : counts) {
if (c != 0) {
match = false;
break;
}
}
if (match) {
return true;
}
}
return false;
}
public static void main(String[] args) {
String[][] cases = {{"ab", "xbay"}, {"abc", "cbxab"}, {"ad", "dad"}, {"abcd", "abc"}};
for (String[] c : cases) {
System.out.println("p=\"" + c[0] + "\", s=\"" + c[1] + "\" -> " + containsPermutation(c[0], c[1]));
}
}
}
p="ab", s="xbay" -> true p="abc", s="cbxab" -> false p="ad", s="dad" -> true p="abcd", s="abc" -> false
Time complexity: O(n × m) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Sliding Window Counts | O(n) | O(1) |
| Recount Each Window | O(n × m) | O(1) |
Here n is the length of s and m the length of p. The sliding window does constant work per position; recounting does m work per position.
Interview Tips and Recommended Approach
- Recognise the fixed window. A permutation has the same length as
p, so the window size never changes. - Update, do not recount. One increment and one decrement per slide is the whole optimisation.
- Mention the matches counter. Tracking how many of the 26 letters currently match avoids comparing whole arrays.
- Know the sibling problem: returning every start index instead of
true/falseuses the same window.
Recommended Approach: Sliding Window Counts
Why: it scans s once with two fixed-size arrays, which is the expected linear-time answer and the template for many anagram-window problems.