Back to Dashboard

Permutation in a String

Medium

Problem Statement

Given a string and a pattern, find out if the string contains any permutation of the pattern.

Permutation is defined as the re-arranging of the characters of the string. For example, “abc” has the following six permutations:

abc acb bac bca cab cba

If a string has n distinct characters, it will have n! permutations.

Examples

Example 1:

  • Input: str = "oidbcaf", pattern = "abc"
  • Output: true

Approach 1 Sliding Window:

 class Solution {
    public boolean checkInclusion(String s1, String s2) {
        var windowStart = 0;
        var charMap = new HashMap<Character, Integer>();
        var matched = 0;
        for (int i = 0; i < s1.length(); i ++) {
            charMap.put(s1.charAt(i), charMap.getOrDefault(s1.charAt(i), 0) + 1);
        }
        for (int windowEnd = 0; windowEnd < s2.length(); windowEnd ++) {
            var endChar = s2.charAt(windowEnd);
            if (charMap.containsKey(endChar)) {
                charMap.put(endChar, charMap.get(endChar) - 1);
                if (charMap.get(endChar) == 0) {
                    matched ++;
                }
            }
            if (matched == charMap.size()) {
                return true;
            }
            while (windowEnd - windowStart + 1 >= s1.length()) {
                var startChar = s2.charAt(windowStart);
                if (charMap.containsKey(startChar)) { 
                    if (charMap.get(startChar) == 0) {
                        matched --;
                    }
                    charMap.put(startChar, charMap.get(startChar) + 1);
                }
                windowStart ++;
            }
        }
        return false;
    }
}

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

StringSliding Window

Date

2026-02-17
View Problem Source