Permutation in String

Algorithms
Medium
IBM
58.3K views

Given two strings $s1$ and $s2$, return true if $s2$ contains a permutation of $s1$, or false otherwise. Use a fixed-size Sliding Window and frequency maps.

Why Interviewers Ask This

IBM interviewers ask this to evaluate a candidate's ability to optimize space complexity beyond brute force. They specifically test if you can recognize that checking all permutations is inefficient and instead apply the sliding window technique with frequency maps. This demonstrates mastery of string manipulation, hash map operations, and algorithmic efficiency under constraints.

How to Answer This Question

1. Clarify requirements: Confirm if case sensitivity matters or if only lowercase English letters are used, as IBM values precise problem scoping. 2. Analyze constraints: Note that since s1 length determines the window size, you do not need to generate permutations. 3. Define the strategy: Propose using a fixed-size sliding window over s2 equal to s1's length. 4. Initialize structures: Create two frequency arrays or maps for s1 and the current window in s2. 5. Execute the slide: Iterate through s2, updating the window by adding the new character and removing the one leaving the window. 6. Compare states: Check if the current window map matches the s1 map exactly after each update. 7. Optimize: Discuss how comparing maps can be optimized by tracking a match count variable to avoid O(26) comparisons on every step.

Key Points to Cover

  • Recognize that generating permutations is unnecessary; focus on character counts instead
  • Correctly implement a fixed-size sliding window based on s1's length
  • Use frequency maps (or arrays) to track character occurrences efficiently
  • Optimize the comparison step to avoid linear scanning of the map on every iteration
  • Demonstrate understanding of O(N) time complexity and O(1) space complexity

Sample Answer

To solve the Permutation in String problem efficiently, I would first clarify that we are looking for an exact substring match of any permutation of s1 within s2. A brute-force approach generating all permutations of s1…

Common Mistakes to Avoid

  • Attempting to generate all permutations of s1, leading to exponential time complexity
  • Using a dynamic window size instead of fixing it to the length of s1
  • Comparing substrings directly instead of comparing frequency counts
  • Failing to handle edge cases where s1 is longer than s2 or strings contain special characters

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 145 Algorithms questionsBrowse all 29 IBM questions