Hone logo
Hone
Problems

Permutation in String

Given two strings, s1 and s2, determine if s2 contains a permutation of s1 as a substring. A permutation of a string is a rearrangement of its characters. This problem is fundamental in string manipulation and has applications in pattern matching and text analysis.

Problem Description

You are tasked with creating a function that checks if any permutation of string s1 exists as a contiguous substring within string s2.

Key Requirements:

  • The function should return true if a permutation of s1 is found as a substring in s2.
  • The function should return false otherwise.
  • The check must be for a contiguous substring. This means the characters forming the permutation must be adjacent in s2.

Expected Behavior:

  • If s1 is empty, it is considered a permutation of itself and is present in any string s2 (even an empty s2).
  • If s1 is longer than s2, no permutation of s1 can exist as a substring in s2.

Edge Cases:

  • Empty strings for s1 and s2.
  • Strings with repeated characters.
  • s1 being longer than s2.

Examples

Example 1:

Input: s1 = "ab", s2 = "eidbaooo"
Output: true
Explanation: s2 contains one permutation of s1: "ba" as a substring.

Example 2:

Input: s1 = "ab", s2 = "eidboaoo"
Output: false
Explanation: No permutation of "ab" (i.e., "ab" or "ba") exists as a contiguous substring in "eidboaoo".

Example 3:

Input: s1 = "adc", s2 = "dcda"
Output: true
Explanation: s2 contains a permutation of s1: "cda" as a substring.

Constraints

  • 1 <= s1.length, s2.length <= 10^4
  • s1 and s2 consist of lowercase English letters.
  • The solution should aim for an efficient time complexity, ideally linear or close to linear with respect to the length of s2.

Notes

Consider how you can efficiently compare character counts between substrings of s2 and the string s1. Think about sliding window techniques and how to maintain character frequencies.

Loading editor...
plaintext