Given an array** string[]** consisting of N numeric strings of length M, the task is to find the number of distinct strings that can be generated by selecting any two strings, say i and j from the array and swap all possible prefixes between them.

_Note: _Since the answer can be very large, print modulo 1000000007.

Examples:

Input:_ N = 2 M = 3 string[] = {“112”, “211”}_

Output:_ 4_

Explanation:

Swapping “1” and “2” between the strings generates “212” and “111“.

Swapping “11” and “21” between the strings generates “212” and “111”.

Swapping “112” and “211” between the strings generates “211” and “112“.

Therefore, 4 distinct strings are generated.

_Input: _N = 4 M = 5 string[] = {“12121”, “23545”, “11111”, “71261”}

_Output: _216

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: Considering a string s of the form s1s2s3s4…sm, where s1 is the first letter of any of the strings in the array, s2 is the second letter of any of the strings, and so on, the answer to the problem is the product of count(i) where **count(i) **is the count of different letters placed at same index in the given strings.

Below is the implementation of the above approach:

  • Java

// Java Program to implement

// the above approach

**import** java.util.*;

**import** java.io.*;

**public** **class** Main {

**static** **int** mod = 1000000007``;

// Function to count the distinct strings

// possible after swapping the prefixes

// between two possible strings of the array

**public** **static** **long** countS(String str[], **int** n, **int** m)

{

// Stores the count of unique

// characters for each index

Map<Integer, Set<Character> > counts

= **new** HashMap<>();

**for** (``**int** i = 0``; i < m; i++) {

counts.put(i, **new** HashSet<>());

}

**for** (``**int** i = 0``; i < n; i++) {

// Store current string

String s = str[i];

**for** (``**int** j = 0``; j < m; j++) {

counts.get(j).add(s.charAt(j));

}

}

// Stores the total number of

// distinct strings possible

**long** result = 1``;

**for** (``**int** index : counts.keySet())

result = (result

* counts.get(index).size())

% mod;

// Return the answer

**return** result;

}

// Driver Code

**public** **static** **void** main(String[] args)

{

String str[] = { "112"``, "211" };

**int** N = 2``, M = 3``;

System.out.println(countS(str, N, M));

}

}

Output:

4

Time Complexity:_ O(N * M)_

Auxiliary Space:_ O(N)_

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

#arrays #hash #mathematical #searching #strings #frequency-counting

Count of distinct Strings possible by swapping prefixes of pairs of Strings
6.70 GEEK