Count of valid pairs (X, Y) from given strings such that concatenating X

Count of valid pairs (X, Y) from given strings such that concatenating X

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

Given an array arr[] **of N strings. Let **X and Y be two strings, X **and Y** are said to bevalid pair if the rearrangement of the resultant string from the concatenation of X with X (i.e., X+X) gives Y. The task is to count the number of such valid pairs.

Examples:

Input:_ N = 4, arr[] = {“hacker”, ”ackerhackerh”, ”int”, ”iittnn”, ”long”}_

Output:_ 2 _

Explanation:

Pair {“hacker”, ”ackerhackerh”} “hacker” When concatenated with “hacker” gives ”ackerhackerh” after rearrangement.

_Pair {“int”, ”iittnn”} “int” When concatenated with “int” gives ”iittnn” after rearrangement. _

Input:_ N = 3, arr[] = {“easy”, ”yeasseay“, “medium“} _

Output:1

Explanation:

Pair {“easy”, ”yeasseay“} “easy” When concatenated with “easy” gives ”yeasseay“ after rearrangement.

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

Naive Approach: The idea is to generate all possible pairs and check if any pairs form a valid pair as per the given condition or not. If yes then count this pair and check for the next pair. Print the value of count after the above steps.

Time Complexity:_ O(N2)_

Auxiliary Space:_ O(1)_

Efficient Approach: The idea is to store the sorted string in Hashmap along with its count and iterate through each string of the array concatenate it with itself and find its count in Hashmap add it to the count of pairs. Below are the steps:

  1. Create a hashmap.
  2. Sort the given strings in the array and store its count in hashmap.
  3. Again iterate through all strings and concatenate each string with itself sort the string and find its count in Hashmap.
  4. Update the final count in the above step and print the final count after all the above steps.

Below is the implementation of the above approach:

  • Java
  • Python3

// Java program for the above approach

**import** java.util.*;

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

// Function that count total number

// of valid pairs

**public** **static** **int**

countPairs(String arr[], **int** N)

{

// Create hashmap to store the

// frequency of each string

// in sorted form

HashMap<String, Integer> map

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

// Initialise the count of pairs

**int** count = 0``;

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

String s = sort(arr[i]);

// Store each string in sorted

// form along with it's count

map.put(s, map.getOrDefault(s, 0``) + 1``);

}

// Iterate through each string

// in the array

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

// Concatenate each string with itself

String s = sort(arr[i] + arr[i]);

// Find its count in the hashmap

count += map.getOrDefault(s, 0``);

}

// Return answer

**return** count;

}

// Function to implement sorting on

// strings

**public** **static** String sort(String s)

{

// Convert string to char array

**char** ch[] = s.toCharArray();

// Sort the array

Arrays.sort(ch);

StringBuffer sb = **new** StringBuffer();

**for** (``**char** c : ch)

sb.append(c);

// Return string

**return** sb.toString();

}

// Driver Code

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

{

**int** N = 3``;

// Given array of strings

String arr[] = { "easy"``, "yeasseay"``,

"medium" };

// Function Call

System.out.println(countPairs(arr, N));

}

}

Output: 

1

Time Complexity:_ O(N)_

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.

hash sorting strings

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Minimize Cost to sort a String in Increasing Order

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

Sort an array of strings lexicographically based on prefix

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

The Immutable Strings and the String Pool

In this blog, we are going to find the answers of why string is immutable and how strings literals are stored in String Pool

Heap Sort Explained

As you may know, heapsort is also one of the most asked sorting algorithms besides mergesort and quicksort and today we’re going to talk.

Sort a String in order of values after removal of values smaller than X

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.