


In this problem, we need to select a pair of strings and swap their first characters. After that, we need to calculate the total number of new pairs. We can solve this problem by swapping the first character of each pair and checking if it exists in the array.
An efficient way to solve this problem is to use a hash map data structure.
Problem Statement - We have an array containing N strings. We can select any two strings from all array elements and swap the first characters of these two strings. We need to count the total number of new string pairs generated that are not present in the array.
ExampleExample
Input – array[] = {"should", "would", "can"};
Output – 3
Explanation – The newly generated pair can be could and wan. Another pair could be who and should. The third pair could be san and chould.
Input – array[] = {"demo", "test"};
Output – 1
Explanation – The newly generated pair that does not exist in the array is temo and dest.
method 1
In this method, we will use two nested loops to get all pairs of array elements. After that we will swap the first characters of the two pairs. Next, we'll use a third nested loop to check if the array contains the pair.
algorithm
Define the "cnt" variable and initialize it to 0 to store the total number of pairs.
Use two nested loops to iterate through the string array and get each pair of array elements.
Get the current pair of two strings.
If the first characters of the two strings are not equal, swap them
Define the "isFirst" and "isSecond" variables and initialize them with false to track whether the newly generated string is present in the array.
Use the third nested loop to check if there is a newly generated string in the array. Additionally, the values of the isFirst and isSecond variables are updated based on the strings in the array.
If there is neither the first string nor the second string in the array, increase the value of 'cnt' by 1.
Return the value of the 'cnt' variable.
Example
#include <iostream> using namespace std; // function to find the count of pairs of strings that can be formed by swapping the first character of the strings int newStringPairs(string array[], int len){ // Stores the count of pairs int cnt = 0; // Get all the pairs of strings for (int i = 0; i < len; i++){ for (int j = i + 1; j < len; j++){ // store single pair of strings string first = array[i], second = array[j]; // If both strings' first characters are not equal, swap them. if (first[0] != second[0]){ swap(first[0], second[0]); bool isFirst = false; bool isSecond = false; // Check whether the strings are present in the array or not for (int k = 0; k < len; k++){ if (array[k] == first){ isFirst = true; } if (array[k] == second){ isSecond = true; } } // If both the strings are present in the array, then increment the cnt by 1 if (isFirst == false && isSecond == false){ cnt++; } } } } return cnt; } int main(){ string array[] = {"should", "would", "can"}; int N = sizeof(array) / sizeof(array[0]); cout << "Total number of new pairs we can generate by swapping the first characters of given strings is " << newStringPairs(array, N); return 0; }
Output
Total number of new pairs we can generate by swapping the first characters of given strings is 3
Time complexity - O(N^3), because we use three nested loops.
Space complexity – O(1)
Method Two
In this method, we will use the map data structure to store all the array values in the map. Afterwards, we can check if the map contains the newly generated string. If not, we can increase the count by 1.
algorithm
Define variable ‘cnt’
Loop through the string array and store all array values in the map.
Use two nested loops to get all pairs of array elements.
Get pairs of strings and store them in the "first" and "second" variables.
If the first characters of two strings are not equal, swap them.
In the map, check whether the newly generated string is included. If not, increase the value of "cnt" by 1.
Return the 'cnt' value.
Example
#include <iostream> #include <unordered_map> using namespace std; // function to find the count of pairs of strings that can be formed by swapping the first character of the strings int newStringPairs(string array[], int len){ // to store the total number of new pairs int cnt = 0; // add all strings to the array map unordered_map<string, int> str_map; for (int i = 0; i < len; i++){ str_map[array[i]]++; } //find all pairs of strings that can be formed by swapping the first character of the strings for (int i = 0; i < len; i++){ for (int j = i + 1; j < len; j++){ // get the current pair of strings string first = array[i]; string second = array[j]; // If the first character of both strings is not the same, then swap them if (first[0] != second[0]){ swap(first[0], second[0]); // If both strings are not present in the map, then the increment count if (str_map[first] == 0 && str_map[second] == 0){ cnt++; } } } } return cnt; } int main(){ string array[] = {"should", "would", "can"}; int N = sizeof(array) / sizeof(array[0]); cout << "Total number of new pairs we can generate by swapping the first characters of given strings is " << newStringPairs(array, N); return 0; }
Output
Total number of new pairs we can generate by swapping the first characters of given strings is 3
Time complexity - O(N^2), because we use two nested loops.
Space complexity – O(N) because we use mapping to store all array elements.
We learn the total number of newly generated pairs by swapping the first characters of any array elements. We optimized the code for the second method in terms of time complexity, but the first code is better in terms of space complexity.
The above is the detailed content of Counts the number of new string pairs obtained by swapping the first characters of string pairs in the given array. For more information, please follow other related articles on the PHP Chinese website!

MySQL中如何使用SUM函数计算某个字段的总和在MySQL数据库中,SUM函数是一个非常有用的聚合函数,它可以用于计算某个字段的总和。本文将介绍如何在MySQL中使用SUM函数,并提供一些代码示例来帮助读者深入理解。首先,让我们看一个简单的示例。假设我们有一个名为"orders"的表,其中包含了顾客的订单信息。表结构如下:CREATETABLEorde

时隔四个月,ByteDanceResearch与北京大学物理学院陈基课题组又一合作工作登上国际顶级刊物NatureCommunications:论文《TowardsthegroundstateofmoleculesviadiffusionMonteCarloonneuralnetworks》将神经网络与扩散蒙特卡洛方法结合,大幅提升神经网络方法在量子化学相关任务上的计算精度、效率以及体系规模,成为最新SOTA。论文链接:https://www.nature.com

6 月 23 日,澳大利亚量子计算公司 SQC(Silicon Quantum Computing)宣布推出世界上第一个量子集成电路。这是一个包含经典计算机芯片上所有基本组件的电路,但体量是在量子尺度上。SQC 团队使用这种量子处理器准确地模拟了一个有机聚乙炔分子的量子态——最终证明了新量子系统建模技术的有效性。「这是一个重大突破,」SQC 创始人 Michelle Simmons 说道。由于原子之间可能存在大量相互作用,如今的经典计算机甚至难以模拟相对较小的分子。SQC 原子级电路技术的开发将

一种受欢迎的通用编程语言是Python。它被应用于各种行业,包括桌面应用程序、网页开发和机器学习。幸运的是,Python具有简单易懂的语法,适合初学者使用。在本文中,我们将使用Python来计算矩阵的右对角线之和。什么是矩阵?在数学中,我们使用一个矩形排列或矩阵,用于描述一个数学对象或其属性,它是一个包含数字、符号或表达式的矩形数组或表格,这些数字、符号或表达式按行和列排列。例如−234512367574因此,这是一个有3行4列的矩阵,表示为3*4矩阵。现在,矩阵中有两条对角线,即主对角线和次对

本文由Cristian Bodnar 和Fabrizio Frasca 合著,以 C. Bodnar 、F. Frasca 等人发表于2021 ICML《Weisfeiler and Lehman Go Topological: 信息传递简单网络》和2021 NeurIPS 《Weisfeiler and Lehman Go Cellular: CW 网络》论文为参考。本文仅是通过微分几何学和代数拓扑学的视角讨论图神经网络系列的部分内容。从计算机网络到大型强子对撞机中的粒子相互作用,图可以用来模

使用Python的abs()函数计算数值的绝对值绝对值是一个数与零点的距离,无论这个数是正数还是负数,其绝对值都是非负数。在Python中,我们可以使用内置函数abs()来计算一个数的绝对值。本文将详细介绍abs()函数的使用方法,并给出一些代码示例。abs()函数的语法如下:abs(x)其中,x是需要计算绝对值的数值。下面是一些使用abs()函数的示例:示

清华大学举办的一场机器人版猫捉老鼠游戏,登上了Science子刊封面。这里的汤姆猫有了新的名字:“天机猫”,它搭载了清华大学类脑芯片的最新研究成果——一款名为TianjicX的28nm神经形态计算芯片。它的任务是抓住一只随机奔跑的电子老鼠:在复杂的动态环境下,各种障碍被随机地、动态地放置在不同的位置,“天机猫”需要通过视觉识别、声音跟踪或两者结合的方式来追踪老鼠,然后在不与障碍物碰撞的情况下向老鼠移动,最终追上它。在此过程中,“天机猫”需要实现实时场景下的语音识别、声源定位、目标检测、避障和决

阿里云机器学习平台PAI与华东师范大学高明教授团队合作在SIGIR2022上发表了结构感知的稀疏注意力Transformer模型SASA,这是面向长代码序列的Transformer模型优化方法,致力于提升长代码场景下的效果和性能。由于self-attention模块的复杂度随序列长度呈次方增长,多数编程预训练语言模型(Programming-basedPretrainedLanguageModels,PPLM)采用序列截断的方式处理代码序列。SASA方法将self-attention的计算稀疏化


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
