JavaScript Program to Decode a String Recursively Encoded as Count Followed by Substring Last Updated : 05 Oct, 2023 Comments Improve Suggest changes Like Article Like Report Given an encoded string, the encoding is done as follows: The string is divided into substrings. Each substring is followed by a number, representing the count of times that substring should be repeated. The task is to decode this encoded string recursively and return the decoded string. <count>[sub_str] ==> The substring 'sub_str' appears count times.Examples: Input : str[] = "2[ni]"Output : niniInput : str[] = "2[f2[k]]"Output : fkkfkkInput : str[] = "3[b2[ca]]"Output : bcacabcacabcacaTable of ContentUsing two StacksWithout StacksApproach 1: Using two StacksInitialize two stacks: one for integers (let's call it the integer stack) and the other for characters (the character stack).Traverse the input string character by character.When encountering a number, push it onto the integer stack.If you encounter an alphabet character (from 'a' to 'z') or an open bracket ('['), push it onto the character stack.If a closing bracket (']') is encountered, perform the following steps:Pop characters from the character stack until an open bracket ('[') is encountered.Pop the top element from the integer stack, denoted as 'n'.Create a string by repeating the characters obtained in the previous step 'n' times.Push each character of the generated string back onto the character stack.Continue this process until the entire string is traversed.Example:This example shows the use of the above-explained appraoch. JavaScript // Javascript program to decode a string recursively // encoded as count followed substring // Returns decoded string for 'str' function decode(str) { let integerstack = []; let stringstack = []; let temp = "", result = ""; // Traversing the string for (let i = 0; i < str.length; i++) { let count = 0; // If number, convert it into number // and push it into integerstack. if (str[i] >= "0" && str[i] <= "9") { while (str[i] >= "0" && str[i] <= "9") { count = count * 10 + str[i] - "0"; i++; } i--; integerstack.push(count); } // If closing bracket ']', pop element // until '[' opening bracket is not found // in the character stack. else if (str[i] == "]") { temp = ""; count = 0; if (integerstack.length > 0) { count = integerstack[integerstack.length - 1]; integerstack.pop(); } while ( stringstack.length > 0 && stringstack[stringstack.length - 1] != "[" ) { temp = stringstack[stringstack.length - 1] + temp; stringstack.pop(); } if ( stringstack.length > 0 && stringstack[stringstack.length - 1] == "[" ) { stringstack.pop(); } // Repeating the popped string 'temo' // count number of times. for (let j = 0; j < count; j++) { result = result + temp; } // Push it in the character stack. for (let j = 0; j < result.length; j++) { stringstack.push(result[j]); } result = ""; } // If '[' opening bracket, push it // into character stack. else if (str[i] == "[") { if (str[i - 1] >= "0" && str[i - 1] <= "9") { stringstack.push(str[i]); } else { stringstack.push(str[i]); integerstack.push(1); } } else { stringstack.push(str[i]); } } // Pop all the element, make a // string and return. while (stringstack.length > 0) { result = stringstack[stringstack.length - 1] + result; stringstack.pop(); } return result; } let str = "3[f2[jk]]"; console.log(decode(str)); Outputfjkjkfjkjkfjkjk Approach 2: Without StacksAlgorithm for better understanding. Initialize an empty string to store the decoded output.Traverse the input string character by character.If the current character is not a closing bracket (']'), simply add it to the output string.If the current character is a closing bracket (']'), it indicates the end of a substring. We need to extract the substring enclosed within the corresponding opening bracket ('[') and determine the number of times it needs to be repeated. We'll use a variable, let's call it num, to store this count.Once we have extracted num and substring, append substring to the output string num times. This replicates the decoding process where substring is repeated num times.Continue steps 3-5 until we reach the end of the input string.Finally, return the decoded string, which is the result after processing the entire input.Example: Below is the implementation of the above approach. JavaScript // Function to decode given encoded string function decodeString(s) { let result = ""; for (let i = 0; i < s.length; i++) { if (s[i] !== "]") { // If the current character is // not a closing bracket, // append it to the result string. result += s[i]; } else { // If the current character is // a closing bracket: // Create a temporary string to // store the substring within // the corresponding opening bracket. let temp = ""; while ( result.length > 0 && result[result.length - 1] !== "[" ) { // Keep popping characters from the // result string and add them to the // temp string until we reach the opening bracket. temp = result[result.length - 1] + temp; result = result.slice(0, -1); } result = result.slice(0, -1); // Remove the opening bracket // Extract the preceding number and convert it to an integer. let num = ""; while ( result.length > 0 && !isNaN(result[result.length - 1]) ) { // Keep popping characters from the // result string and add them to // num string // until we encounter a non-digit character. num = result[result.length - 1] + num; result = result.slice(0, -1); } let int_num = parseInt(num); // Append the substring to the result string, // repeat it to the required number of times. while (int_num--) { result += temp; } } } // Return the decoded string. return result; } // Driver code to test above function let str = "2[1[a]2[b]]"; console.log(decodeString(str)); Outputabbabb Comment More infoAdvertise with us Next Article JavaScript Program to Decode a String Recursively Encoded as Count Followed by Substring A anjugaeu01 Follow Improve Article Tags : JavaScript Web Technologies javascript-string JavaScript-DSA JavaScript-Program +1 More 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 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 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 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 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 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 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 Like