You are given a string s and an array of strings words. All the strings of words are of the same length.
A concatenated string is a string that exactly contains all the strings of any permutation of words concatenated.
For example, if words = ["ab","cd","ef"], then "abcdef", "abefcd", "cdabef", "cdefab", "efabcd", and "efcdab" are all concatenated strings. "acdbef" is not a concatenated string because it is not the concatenation of any permutation of words.
Return an array of the starting indices of all the concatenated substrings in s. You can return the answer in any order.
Example 1:
Input: s = "barfoothefoobarman", words = ["foo","bar"]
Output: [0,9]
Explanation:
The substring starting at 0 is "barfoo". It is the concatenation of ["bar","foo"] which is a permutation of words.
The substring starting at 9 is "foobar". It is the concatenation of ["foo","bar"] which is a permutation of words.
Example 2:
Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
Output: []
Explanation:
There is no concatenated substring.
Example 3:
Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
Output: [6,9,12]
Explanation:
The substring starting at 6 is "foobarthe". It is the concatenation of ["foo","bar","the"].
The substring starting at 9 is "barthefoo". It is the concatenation of ["bar","the","foo"].
The substring starting at 12 is "thefoobar". It is the concatenation of ["the","foo","bar"].
Constraints:
1 <= s.length <= 104
1 <= words.length <= 5000
1 <= words[i].length <= 30
s and words[i] consist of lowercase English letters.
/**
Note: The returned array must be malloced, assume caller calls free().
/
int findSubstring(char* s, char** words, int wordsSize, int* returnSize) {
}
Assistant
To solve this problem, we need to find all starting indices in the string s where a concatenation of all the words in the words array appears exactly once and without any intervening characters. All the words are of the same length, which is a crucial detail that allows us to optimize our approach.
Approach Overview:
Edge Case Handling:
If either s or words is empty, or if the total length of concatenated words exceeds the length of s, return an empty result.
Preprocessing:
Calculate the length of each word (word_len) and the total length of all concatenated words (total_len).
Create a frequency map (word_count) to store the number of times each word appears in the words array.
Sliding Window Technique:
Iterate through s with different starting offsets (from 0 to word_len - 1).
For each offset, use a sliding window of size total_len to check if the substring is a valid concatenation of all words.
Within the window, extract words of length word_len and verify their presence and frequency in the word_count map.
If a valid concatenation is found, record the starting index.
Hash Map Implementation:
Since C doesn't have a built-in hash map, we'll implement a simple hash map using separate chaining (linked lists) to handle collisions.
This custom hash map will store words and their frequencies, allowing efficient lookup and insertion.
Result Construction:
Dynamically allocate memory to store the resulting starting indices.
Return the array of indices along with its size.
Complete C Implementation:
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define the structure for hash map's entry
typedef struct Entry {
char* key;
int value;
struct Entry* next;
} Entry;
// Define the structure for hash map
typedef struct {
int size; // Number of buckets
Entry** buckets;
} HashMap;
// Function to create a new hash map
HashMap* createHashMap(int size) {
HashMap* map = (HashMap*)malloc(sizeof(HashMap));
map->size = size;
map->buckets = (Entry**)malloc(sizeof(Entry*) * size);
for(int i = 0; i < size; i++) {
map->buckets[i] = NULL;
}
return map;
}
// Simple hash function (djb2)
unsigned long hashFunction(const char* str) {
unsigned long hash = 5381;
int c;
while((c = *str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
// Function to insert or update a key in the hash map
void setHashMap(HashMap* map, const char* key, int value) {
unsigned long hash = hashFunction(key);
int index = hash % map->size;
Entry* entry = map->buckets[index];
while(entry != NULL) {
if(strcmp(entry->key, key) == 0){
entry->value = value;
return;
}
entry = entry->next;
}
// If key not found, create new entry
Entry* newEntry = (Entry*)malloc(sizeof(Entry));
newEntry->key = strdup(key);
newEntry->value = value;
newEntry->next = map->buckets[index];
map->buckets[index] = newEntry;
}
// Function to get the value for a key in the hash map
int getHashMap(HashMap* map, const char* key, int* found) {
unsigned long hash = hashFunction(key);
int index = hash % map->size;
Entry* entry = map->buckets[index];
while(entry != NULL) {
if(strcmp(entry->key, key) == 0){
*found = 1;
return entry->value;
}
entry = entry->next;
}
*found = 0;
return 0;
}
// Function to free the hash map
void freeHashMap(HashMap* map) {
for(int i = 0; i < map->size; i++) {
Entry* entry = map->buckets[i];
while(entry != NULL){
Entry* temp = entry;
entry = entry->next;
free(temp->key);
free(temp);
}
}
free(map->buckets);
free(map);
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* findSubstring(char* s, char** words, int wordsSize, int* returnSize) {
*returnSize = 0;
if(s == NULL || wordsSize == 0) return NULL;
int s_len = strlen(s);
int word_len = strlen(words[0]);
int total_len = word_len * wordsSize;
if(s_len < total_len) return NULL;
// Initialize hash maps
// Choosing a prime number for hash map size to reduce collisions
int hash_map_size = 10007;
HashMap* word_count = createHashMap(hash_map_size);
HashMap* window_count = createHashMap(hash_map_size);
// Build the frequency map for words
for(int i = 0; i < wordsSize; i++) {
int found;
int cnt = getHashMap(word_count, words[i], &found);
if(found){
setHashMap(word_count, words[i], cnt + 1);
}
else{
setHashMap(word_count, words[i], 1);
}
}
// Allocate memory for result
// Maximum possible is s_len
int* result = (int*)malloc(sizeof(int) * s_len);
int res_count = 0;
// Iterate through word_len different offsets
for(int i = 0; i < word_len; i++) {
int left = i;
int right = i;
// Reset window_count
// For efficiency, we'll reuse the window_count map
// First, clear all counts
for(int j = 0; j < window_count->size; j++) {
Entry* entry = window_count->buckets[j];
while(entry != NULL){
entry->value = 0;
entry = entry->next;
}
}
int count = 0;
while(right + word_len <= s_len) {
char word[31];
strncpy(word, s + right, word_len);
word[word_len] = '\0';
right += word_len;
int found;
int wc = getHashMap(word_count, word, &found);
if(found){
// Update window count
int current = getHashMap(window_count, word, &found);
setHashMap(window_count, word, current + 1);
if(current + 1 > wc){
// Move left to reduce count
while(current + 1 > wc){
char left_word[31];
strncpy(left_word, s + left, word_len);
left_word[word_len] = '\0';
setHashMap(window_count, left_word, getHashMap(window_count, left_word, &found) - 1);
left += word_len;
count--;
if(strcmp(left_word, word) == 0){
break;
}
}
}
count++;
if(count == wordsSize){
result[res_count++] = left;
// Move left to find new window
char left_word[31];
strncpy(left_word, s + left, word_len);
left_word[word_len] = '\0';
setHashMap(window_count, left_word, getHashMap(window_count, left_word, &found) - 1);
left += word_len;
count--;
}
}
else{
// Reset window
for(int j = 0; j < window_count->size; j++) {
Entry* entry = window_count->buckets[j];
while(entry != NULL){
entry->value = 0;
entry = entry->next;
}
}
left = right;
count = 0;
}
}
}
freeHashMap(word_count);
freeHashMap(window_count);
if(res_count == 0){
free(result);
return NULL;
}
// Resize the result array to the actual count
int* final_result = (int*)malloc(sizeof(int) * res_count);
memcpy(final_result, result, sizeof(int) * res_count);
free(result);
*returnSize = res_count;
return final_result;
}
// Example usage and testing
int main(){
char s1[] = "barfoothefoobarman";
char* words1[] = {"foo","bar"};
int wordsSize1 = 2;
int returnSize1;
int* result1 = findSubstring(s1, words1, wordsSize1, &returnSize1);
printf("Output: [");
for(int i = 0; i < returnSize1; i++){
printf("%d", result1[i]);
if(i != returnSize1 -1) printf(",");
}
printf("]\n");
free(result1);
char s2[] = "wordgoodgoodgoodbestword";
char* words2[] = {"word","good","best","word"};
int wordsSize2 = 4;
int returnSize2;
int* result2 = findSubstring(s2, words2, wordsSize2, &returnSize2);
printf("Output: [");
for(int i = 0; i < returnSize2; i++){
printf("%d", result2[i]);
if(i != returnSize2 -1) printf(",");
}
printf("]\n");
free(result2);
char s3[] = "barfoofoobarthefoobarman";
char* words3[] = {"bar","foo","the"};
int wordsSize3 = 3;
int returnSize3;
int* result3 = findSubstring(s3, words3, wordsSize3, &returnSize3);
printf("Output: [");
for(int i = 0; i < returnSize3; i++){
printf("%d", result3[i]);
if(i != returnSize3 -1) printf(",");
}
printf("]\n");
free(result3);
return 0;
}
Explanation of the Code:
Hash Map Implementation:
Structures:
Entry: Represents each key-value pair in the hash map, including a pointer to handle collisions via separate chaining.
HashMap: Contains the size of the hash map and an array of pointers to Entry nodes.
Functions:
createHashMap: Initializes a hash map with a specified number of buckets.
hashFunction: Implements the djb2 algorithm, a widely used hash function for strings.
setHashMap: Inserts a new key or updates the value of an existing key.
getHashMap: Retrieves the value associated with a key, indicating whether the key was found.
freeHashMap: Frees all allocated memory for the hash map.
Main Function (findSubstring):
Initialization:
Calculate lengths and handle edge cases.
Initialize two hash maps: word_count to store the frequency of each word in words, and window_count to keep track of word frequencies within the current sliding window.
Building Frequency Map:
Iterate over words and populate word_count with the frequency of each word.
Sliding Window Processing:
Iterate through s with different starting offsets to cover all possible alignments.
For each alignment, reset window_count and use two pointers (left and right) to define the current window.
Extract substrings of length word_len and update window_count.
If the frequency of a word exceeds its required count, adjust the left pointer to maintain validity.
When a valid concatenation is found (i.e., the number of matched words equals wordsSize), record the left index.
Result Compilation:
After processing, allocate a result array with the exact number of valid starting indices found.
Free the temporary hash maps and return the result.
Notes:
Memory Management: Ensure that all dynamically allocated memory (especially within the hash maps) is properly freed to avoid memory leaks.
Hash Map Size: A prime number (10007) is chosen for the hash map size to reduce collision probability. Adjusting the size might be necessary based on different input sizes.
Performance: While this implementation is efficient for the given constraints, further optimizations (like using more efficient string comparison or hash functions) can be considered for larger inputs.
Conclusion:
This C implementation effectively finds all starting indices of concatenated substrings formed by any permutation of the words array within the string s. By leveraging hash maps for frequency counting and the sliding window technique, the solution ensures both accuracy and efficiency within the problem's constraints.
Not yet included in a published release.
Testing:
The main function includes test cases corresponding to the examples provided:
Example 1:
Input: s = "barfoothefoobarman", words = ["foo","bar"]
Output: [0,9]
Example 2:
Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
Output: []
Example 3:
Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]