String Expansion - Amazon Top Interview Questions

Problem Statement :

You are given a string s consisting of lowercase alphabet characters, digits, and brackets"(" and ")". s encodes a longer string and is represented as concatenation of n(t), where n is the number of times t is repeated, and t is either a regular string or it's another encoded string recursively.

Return the expanded version of s. Note that t can be the empty string.

Example 1


s = "2(ye)0(z)2(2(po)w)"



Solution :


                        Solution in C++ :

string solve(string s) {
    stack<string> sk;
    stack<int> cnt;
    for (int i = 0; i < s.size(); i++) {
        if (isdigit(s[i])) {
            int c = atoi(&s[i]);
            while (i < s.size() && isdigit(s[i])) i++;
        } else if (s[i] == ')') {
            int c =;
            string ss =;
            while (c-- > 0) {
        } else {

                        Solution in Java :

import java.util.*;

class Solution {
    public String solve(String s) {
        return recurse(s);
    public String recurse(String s) {
        if (s.length() == 0)
            return s;
        String ret = "";
        for (int j = 0; j < s.length(); j++) {
            if (Character.isDigit(s.charAt(j))) {
                int start = s.substring(j, s.length()).indexOf("(") + j;
                int x = Integer.parseInt(s.substring(j, start));
                int count = 1;
                int end;
                for (end = start + 1; end < s.length(); end++) {
                    if (s.charAt(end) == '(') {
                    } else if (s.charAt(end) == ')') {

                    if (count == 0) {
                String embed = s.substring(start + 1, end);
                ret += duplicate(recurse(embed), x);
                j += embed.length() + 2;
            } else {
                ret += String.valueOf(s.charAt(j));
        return ret;
    public String duplicate(String s, int x) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < x; i++) {
        return sb.toString();

                        Solution in Python : 
class Solution:
    def solve(self, s):
        if "(" not in s:
            return s

        # where it all starts
        start = s.index("(")

        # i is the position at which digits start,
        # so we can simply take the string before that as-is
        for i in range(len(s)):
            if s[i].isdigit():

        # number of times we need to multiply this string
        count = int(s[i:start])

        # we need to find the position in string that balances the current set of braces
        # so, currently since we already have a '(', balance is 1
        # when balance becomes 0, we have reached the end of the string
        # that we will multiply
        balance = 1
        for end in range(start + 1, len(s)):
            if s[end] == "(":
                balance += 1
            elif s[end] == ")":
                balance -= 1
                if not balance:

        # now we simply return
        # 1. s[:i] = string before integer part
        # 2. count * self.solve(s[start+1: end]) = simply multiply the string between the braces
        #                                           but also solve this substring recursively
        # 3. self.solve(s[end+1:]) = run the recursive function for the remaining string on the right
        return s[:i] + count * self.solve(s[start + 1 : end]) + self.solve(s[end + 1 :])

View More Similar Problems

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →