Problems - Set 1
Problem 1
Given a smaller string s and a bigger string b, find all permutations of s within b and print their starting indices.
Example
Input:
s = "abc"
b = "cbabcacab"
Output:
[0, 3, 5]
Explanation:
"cba"(index0-2) is a permutation of"abc"."bac"(index3-5) is a permutation of"abc"."cab"(index5-7) is a permutation of"abc".
Approach
Use the Sliding Window Technique with Frequency Counting:
Maintain a frequency count (hash map or array) of characters in
s.Use a window of size
len(s)inband check if the frequency of characters in this window matches that ofs.Slide the window across
b, updating the character counts efficiently.
Steps:
Compute the frequency of characters in
susing an arraysFreqof size 26 (for lowercase letters).Maintain a
windowFreqarray to store the frequency of characters in the current window ofb.Initialize
windowFreqwith the firstlen(s)characters ofb.Compare
sFreqandwindowFreq. If they match, store the starting index.Slide the window by:
Removing the leftmost character count.
Adding the new rightmost character count.
Continue this until the end of
b.
Time & Space Complexity
Time Complexity:
Initializing the frequency arrays:
O(N), whereN = len(s).Sliding the window and updating the frequency count:
O(M), whereM = len(b).Overall: O(M + N) ≈ O(M) (since
Nis small compared toM).
Space Complexity:
O(1), since we use fixed-size arrays (sFreqandwindowFreqof size 26).
Code
Last updated