![]() |
VOOZH | about |
Given an array of binary strings arr[] of size N (1 <= N <= 103). The task is to find the maximum distance between any pair of these binary strings. The distance between two binary strings is calculated as the sum of their lengths after excluding the common prefix.
Examples:
Input: arr[] = { “01011”, “010110”, “0111”}
Output: 6
Explanation: The strings with the maximum distance between them are “010110” and “0111”, where the common prefix is “01”, Hence, the sum of their lengths after excluding the common prefix: 4 + 2 = 6.Input: arr[] = {"001", "1", "111111"}
Output: 9
Explanation: The string "001" and "111111" have no common prefix, hence, the sum of their lengths after excluding the common prefix: 3 + 6 = 9.
We need to use of a Trie data structure to efficiently find the maximum distance between binary strings in the given array. We'll store the length of longest suffix from current node till its bottom leaf node. By traversing the Trie, we can find the maximum distance by considering the sum of lengths of non-overlapping substrings of binary strings, resulting in the desired maximum distance calculation. This approach is extremely more efficient than comparing every pair of binary strings directly.
Below is the implementation of the above approach:
6
Time Complexity: O(N * M), where N is the number of binary strings and M is the average length of the binary strings.
Auxiliary Space: O(N * M)