Check if two strings are permutation of each other in JavaScript Last Updated : 27 May, 2024 Comments Improve Suggest changes Like Article Like Report In this approach, we are going to discuss how we can check if two strings are permutations of each other or not using JavaScript language. If two strings have the same number of characters rather than having the same position or not it will be a permutation. Example: Input: "pqrs" , "rpqs"Output: TrueExplanation: Both strings have a same number of characters.These are the approaches by using these we can Check if two strings are permutations of each other or not: Table of Content Using SortingCount charactersUsing MapUsing XOR OperationMethod 1: Using SortingCreating a function and storing the length of strings in separate variables.Checking if the length of both strings is not the same then we will return false. As strings are not permutations of each other.If the length is the same then we will sort both the strings.We will check the presence of the same character in both strings in a for loop. If any of the characters get mismatched then we will return false. else we will return true at the end of the for loop.Example: JavaScript function arePermutation(str1, str2) { // Get lengths of both strings let n1 = str1.length; let n2 = str2.length; // If length of both strings // is not the same, then they // cannot be permutations if (n1 !== n2) return false; // Convert the strings to arrays let ch1 = str1.split(''); let ch2 = str2.split(''); // Sort both arrays ch1.sort(); ch2.sort(); // Compare sorted arrays for (let i = 0; i < n1; i++) if (ch1[i] !== ch2[i]) return false; return true; } // Driver Code let str1 = "test"; let str2 = "teat"; if (arePermutation(str1, str2)) console.log("Yes"); else console.log("No"); OutputNoTime Complexity: O(nLogn) Auxiliary space: O(1) Method 2: Count charactersCreating a counting array of size 256. In which we are counting the number of characters present in both of the strings in two different array.If length of the strings are not same we will return false.We are using for loop for comparing the count of character if the count is not same then we will return false else a the end of for loop it will return true.Example: JavaScript let NO_OF_CHARS = 256; function arePermutation(str1, str2) { // Create 2 count arrays // and initialize all values as 0 let count1 = Array(NO_OF_CHARS).fill(0); let count2 = Array(NO_OF_CHARS).fill(0); if (str1.length !== str2.length) return false; for (let i = 0; i < str1.length && i < str2.length; i++) { count1[str1[i].charCodeAt(0)]++; count2[str2[i].charCodeAt(0)]++; } // Compare count arrays for (let i = 0; i < NO_OF_CHARS; i++) { if (count1[i] !== count2[i]) return false; } return true; } // Driver code let str1 = "geeks"; let str2 = "geeks"; if (arePermutation(str1, str2)) console.log("Yes"); else console.log("No"); OutputYesTime Complexity: O(n) Auxiliary space: O(n). Method 3: Using MapFirst we check if the lengths of both strings are equal. If not, they cannot be permutations, so we return false. Then we create a Map to store the character frequencies of str1 then, we iterate through str2 and decrement the frequencies in the Map. If a character is not found in the Map or its frequency becomes zero, we return false. If all characters in str2 are successfully matched, the Map will be empty, and we return true.Example: JavaScript function arePermutations(str1, str2) { // Check if the lengths of // both strings are the same if (str1.length !== str2.length) { return false; } // Create a Map to store character const charFrequencyMap = new Map(); // Fill the Map with characters for (let char of str1) { charFrequencyMap.set(char, (charFrequencyMap.get(char) || 0) + 1); } // Iterate through str2 for (let char of str2) { if (!charFrequencyMap.has(char)) { // Character not found in str1 return false; } charFrequencyMap.set(char, charFrequencyMap.get(char) - 1); if (charFrequencyMap.get(char) === 0) { charFrequencyMap.delete(char); } } // If the Map is empty // all characters in str2 //have been matched return charFrequencyMap.size === 0; } // Test cases console.log(arePermutations("abc", "cba")); OutputtrueTime complexity: O(n) Space Complexity: O(n) Using XOR OperationUsing XOR operation, XOR all characters in both strings. If the result is zero, the strings have the same characters with the same frequency, indicating they are permutations of each other. Example: In this example The function arePermutations compares lengths, then bitwise XORs character codes of each string. Returns true if the XOR result is 0, indicating permutation JavaScript function arePermutations(str1, str2) { if (str1.length !== str2.length) { return false; } let result = 0; for (let i = 0; i < str1.length; i++) { result ^= str1.charCodeAt(i) ^ str2.charCodeAt(i); } return result === 0; } const string1 = "abc"; const string2 = "bca"; console.log(arePermutations(string1, string2)); const string3 = "abc"; const string4 = "def"; console.log(arePermutations(string3, string4)); Outputtrue false Comment More infoAdvertise with us Next Article Check if two strings are permutation of each other in JavaScript A anjugaeu01 Follow Improve Article Tags : JavaScript Web Technologies javascript-string JavaScript-DSA Similar Reads Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav 11 min read Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De 5 min read Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance 10 min read React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications 15+ min read Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact 12 min read React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon 8 min read JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as 15+ min read Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and 9 min read Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We 9 min read Like