Given two strings s1 and s2 return the location of each permutation of the s1 string within the s2 string.

Solution: Iterate through s2 and select blocks of characters of length equal to that of s1 (for simplicity let's call this block string ref). Now, check if ref is a permutation of s1. To check this we have two possible approaches.Approach #1 (less efficient): Make a copy of the s1 string. Apply an efficient sorting algorithm (e.g. MergeSort or QuickSort) and sort the copy. Apply the same sorting algorithm to sort the ref string. If the resulting strings are equal, it means that ref was indeed a permutation of s1, and as such, return the current location within s2.Approach #2 (optimal): Iterate through the s1 string and build a hashmap, such that each character of s1 becomes a key, and the associated value is the number of apparitions of the given character within s1. Then iterate through the ref string and for each character check if there is a key within the constructed hashmap equal to the current character, which points to a value greater than 0. If it isn't, then break the current search and move to the next block in s2. If it is, decrease the value that the given key points to and continue. At the end check if the hashmap contains only 0 values. If it does, return the current index, otherwise continue the search through s2.Repeat the above process until we have iterated through the entire s2 string.

Related Computing University answers

All answers ▸

What is polymorphism in regards to Object Oriented Programming (OOP)? Provide an example.


Find a given element m in a list of n sorted numbers, with time complexity O(log(n))


Write a recursive binary search algorithm in pseudocode.


What is inheritance in object-oriented programming?


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo

© MyTutorWeb Ltd 2013–2024

Terms & Conditions|Privacy Policy