885662. Check if Permutation is Substring

Easy

Check if Permutation is Substring

Summary

Given two strings s1 and s2, check if s2 is a permutation of a substring in s1. A permutation of a string means rearranging its characters to form another string. The problem requires identifying whether s2 can be formed by rearranging the characters within s1 into a contiguous substring.

Detailed Explanation

To solve this problem, we will use a sliding window approach to check if s2 is a permutation of any substring in s1. Here's the step-by-step breakdown:

  1. Initialize two pointers, start and end, to represent the start and end indices of the sliding window.
  2. Iterate through s1 with the end pointer until the length of the substring between start and end is equal to the length of s2.
  3. Sort the characters in the current substring (using a sorting algorithm like QuickSort or BubbleSort) and store it in an array, arr.
  4. Compare arr with the sorted characters of s2. If they match, it means that s2 is a permutation of the current substring in s1, so return true.
  5. Move the end pointer one step forward and repeat steps 2-4 until the end of s1 is reached.
  6. If no permutation is found, return false.

Time complexity: O(n log n) due to sorting within each substring Space complexity: O(1) as we only use a constant amount of space

Optimized Solutions

Java

View on GeeksforGeeks
public boolean checkPermutation(String s1, String s2) {
    if (s1.length() < s2.length()) return false;
    
    for (int start = 0; start <= s1.length() - s2.length(); start++) {
        int[] arr = new int[256]; // ASCII characters
        for (int end = start; end < start + s2.length(); end++) {
            arr[s1.charAt(end)]++;
        }
        
        boolean isPermutation = true;
        for (int i = 0; i < 256; i++) {
            if (arr[i] != s2.charAt(i) - 'a' + 1) {
                isPermutation = false;
                break;
            }
        }
        
        if (isPermutation) return true;
    }
    
    return false;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.