Interview Question


Country: United States




Comment hidden because of low score. Click to expand.
1
of 1 vote

public static void main(String[] args) {
		System.out.println(reverse("1+2*3-204"));
	}

	/**
	 * Reverse this string 1+2*3-20. Note: 20 must be retained as is. Expected
	 * output: 20-3*2+1
	 */
	public static String reverse(String str) {

		char[] c = str.toCharArray();

		int i = 0;
		Stack<String> st = new Stack<String>();
		while (i < c.length) {
			String t = "";
			while (!st.isEmpty() && isN(st.peek()) && isN(String.valueOf(c[i]))) {
				String k = st.pop();
				t = k + t;
			}
			t += String.valueOf(c[i]);
			st.push(String.valueOf(t));
			i++;
		}

		String ret = "";
		while (!st.isEmpty())
			ret += st.pop();
		return ret;
	}

	public static boolean isN(String str) {
		boolean f = true;
		try {
			Integer.parseInt(str);
		} catch (Exception e) {
			f = false;
		}
		return f;
	}

- sudip.innovates September 22, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

class ReverseString {
public static void main(String[] args) {
String input = "1+2*3-20";

// getBytes() method to convert string
// into bytes[].
byte[] strAsByteArray = input.getBytes();

byte[] result = new byte[strAsByteArray.length];


// Store result in reverse order into the
// result byte[]
for (int i = 0; i < strAsByteArray.length; i++){

result[i] = strAsByteArray[strAsByteArray.length - i - 1];

}
byte temp = result[0];
result[0] = result[1];
result[1] = temp;
System.out.println(new String(result));
}
}

- Syam September 30, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

/*
Reverse this string 1+2*3-20. Note: 20 must be retained as is.
Expected output: 20-3*2+1
 */
public class ReverseEquation {
    public static void main(String[] args) {
        final String input = "1+2*3-20";
        System.out.println(new ReverseEquation().reverse(input));
        //prints 20-3*2+1

    }

    String reverse(String s) {
        BreakIterator b = java.text.BreakIterator.getWordInstance();
        b.setText(s);
        StringBuilder sb = new StringBuilder();
        for (int end = b.last(), start = b.previous(); start != BreakIterator.DONE;
             end = start, start = b.previous()) {
            String w = s.substring(start, end);
            sb.append(w);
        }
        return sb.toString();
    }

}

- Makarand September 22, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverseString(theString):
	operatorList = ['*', '+', '-', '/']
	finalString = ""
	i = len(theString) - 1
	while (i >= 0):
		currentNum = ""
		while (i >= 0 and theString[i] not in operatorList):
			currentNum = theString[i] + currentNum
			i -= 1
		
		totalString += currentNum
		if (i >= 0):
			totalString += theString[i]
		i -= 1

- SK September 22, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def revStr(string):
    newAr = []
    if '20' in string:
        newAr = ['20']
        string = string.replace('20','')
    else:
        newAr = newAr
    i = len(string) - 1
    while i >= 0:
        newAr.append(string[i])
        print(string[i])
        i = i -1
    return(''.join(newAr))

- sulabhchaturvedi08 September 23, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

void ReverseExpression(string &s)
{
	reverse(s.begin(), s.end());
	int start = -1;
	for (int i = 0; i < s.size(); ++i) {
		if (isdigit(s[i])) {
			if (start == -1) {
				start = i;
			}
			if (i + 1 == s.size() ||
				!isdigit(s[i + 1]))
			{
				reverse(s.begin() + start, s.begin() + i + 1);
				start = -1;
			}
		}
	}
}

- Alex September 26, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package string;

import java.util.Scanner;

public class ReverseExp {

public static String reverExp(String s)
{
char[] ch=s.toCharArray();
String res="";int k=0;
for (int i = ch.length-1 ; i >= 0; i--) {
int start=i;
while(i>=0 && ch[i] >=48 && ch[i] <= 57)
{
i--;
}
int end=i+1;

while(end <= start)
{
res=res+ch[end];
end++;
}
if(i>=0) {
res=res+ch[i];}
}
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String: ");
String s=sc.nextLine();
s=reverExp(s);
System.out.println("Reverse of expression: "+s);
}

}

- Anonymous October 22, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package string;

import java.util.Scanner;

public class ReverseExp {

	public static String reverExp(String s)
	{
		char[] ch=s.toCharArray();
		String res="";int k=0;
		for (int i = ch.length-1 ; i >= 0; i--) {
			int start=i;
			while(i>=0 && ch[i] >=48 && ch[i] <= 57)
			{
				i--;
			}
			int end=i+1;
			
			while(end <= start)
			{
				res=res+ch[end];
				end++;
			}
			if(i>=0) {
			res=res+ch[i];}
		}
		return res;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the String: ");
		String s=sc.nextLine();
		s=reverExp(s);
		System.out.println("Reverse of expression: "+s);
	}

}

- Sachin M October 22, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package string;

import java.util.Scanner;

public class ReverseExp {

	public static String reverExp(String s)
	{
		char[] ch=s.toCharArray();
		String res="";int k=0;
		for (int i = ch.length-1 ; i >= 0; i--) {
			int start=i;
			while(i>=0 && ch[i] >=48 && ch[i] <= 57)
			{
				i--;
			}
			int end=i+1;
			
			while(end <= start)
			{
				res=res+ch[end];
				end++;
			}
			if(i>=0) {
			res=res+ch[i];}
		}
		return res;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the String: ");
		String s=sc.nextLine();
		s=reverExp(s);
		System.out.println("Reverse of expression: "+s);
	}

}

- Sachin M October 22, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package string;

import java.util.Scanner;

public class ReverseExp {

	public static String reverExp(String s)
	{
		char[] ch=s.toCharArray();
		String res="";int k=0;
		for (int i = ch.length-1 ; i >= 0; i--) {
			int start=i;
			while(i>=0 && ch[i] >=48 && ch[i] <= 57)
			{
				i--;
			}
			int end=i+1;
			
			while(end <= start)
			{
				res=res+ch[end];
				end++;
			}
			if(i>=0) {
			res=res+ch[i];}
		}
		return res;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the String: ");
		String s=sc.nextLine();
		s=reverExp(s);
		System.out.println("Reverse of expression: "+s);
	}

}

- Sachin M October 22, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var string2 = "1+2*3-20";
var sliceout1= string2.slice(0,6);
var sliceout2= string2.slice(6);


var splitString1= sliceout1.split("");
splitString1.push(sliceout2);

var reverseArray= splitString1.reverse();
console.log(reverseArray);

reverseArray.toString();

console.log("The reversed string is: "+reverseArray);

- Jessica Erazo November 01, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var string2 = "1+2*3-20";
var sliceout1= string2.slice(0,6);
var sliceout2= string2.slice(6);


var splitString1= sliceout1.split("");
splitString1.push(sliceout2);

var reverseArray= splitString1.reverse();
console.log(reverseArray);

reverseArray.toString();

console.log("The reversed string is: "+reverseArray);

- Jessica Erazo November 01, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#generic solution
def reverseString(str1):
lst_str = []
str2 = ''
str3 = ''
str_flag = 0
sy_flag = 0
for i in str1:
if i.isdigit():
if sy_flag == 1:
lst_str.append(str2)
str2 = ''
sy_flag = 0
str2 = str2 + i
str_flag = 1
else:
if str_flag == 1:
lst_str.append(str2)
str2 = ''
str_flag = 0
str2 = i + str2
sy_flag = 1
lst_str.append(str2)
for j in reversed(lst_str):
str3 = str3 + j
return str3

str1 = '1+2*3-20'
print reverseString(str1)
#below one is more generic
str1 = '-41+2**36-20/+6*'
print reverseString(str1)

- RakeshSharma November 03, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#generic solution
def reverseString(str1):
    lst_str = []
    str2 = ''
    str3 = ''
    str_flag = 0
    sy_flag = 0
    for i in str1:
        if i.isdigit():
            if sy_flag == 1:
                lst_str.append(str2)
                str2 = ''
                sy_flag = 0
            str2 = str2 + i    
            str_flag = 1
        else:        
            if str_flag == 1:
                lst_str.append(str2)
                str2 = ''
                str_flag = 0
            str2 = i + str2    
            sy_flag = 1                
    lst_str.append(str2)          
    for j in reversed(lst_str):
        str3 = str3 + j 
    return str3
 
str1 = '1+2*3-20'
print reverseString(str1) 
#below one is more generic   
str1 = '-41+2**36-20/+6*'
print reverseString(str1)

- RakeshSharma November 03, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include<bits/stdc++.h>
using namespace std;

int main()
{
string str;
getline(cin,str);
string output="";
int j;
for(int i=str.length()-1;i>=-1;i--)
{
if(i==-1 || str[i] == '*' || str[i] == '+' || str[i] == '-' || str[i] == '/')
{
int j = i;
j++;
while(str[j] != '*' && str[j] != '-' && str[j] != '+' && str[j] != '/' && str.length() > j)
{
output = output + str[j];
j++;
}
if(i != -1)
output = output + str[i];
}
}
cout<<output<<endl;


return 0;}

- Shubham Garg December 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Reverse the whole string as is. Next reverse the numbers.
Logic remains same as "This is a book" --> "book a is This" excepting , watch out for mathematical operations, as suppose to space.

C Solution:

#include <stdio.h>
#include <string.h>

void ReverseStringUtil(char *str,int start,int end)
{
    char temp;
    while(start < end)
    {
        temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
        
    }
}

int main()
{
    char *str = (char *)malloc(100 * sizeof(char));
    int start, end;
    fgets(str,100,stdin);
    str[strlen(str)-1] = '\0';
    printf("Input string is - %s \n", str);
    ReverseStringUtil(str,0,strlen(str)-1);
    printf("Semi Output String is - %s \n", str);
    int i=0;
    while(str[i]!='\0')
    {
        start = i;
        for(; str[i]!='+'&&str[i]!='\0'&&str[i]!='-'&&str[i]!='*'&&str[i]!='/'&&str[i]!='%';i++);
        end = i-1;
        ReverseStringUtil(str,start,end);
        i++;
    }
    
    printf("Output String is %s \n", str);
    return 0;
}

- gairu.hobbies January 22, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverse_str(string)
  newString= ""
  strArr   = string.chars
  numArr = string.split(/[-,+,*,\/]/)
  operatorArr = ['*', '+', '-', '/']
  i = strArr.length.to_i - 1
  j = numArr.length.to_i - 1
  
  
  while i >= 0 
   a = strArr[i]  
    if operatorArr.include?(a)
      newString = newString + "#{a}"
     i = i - 1
    else
      b = numArr[j]
      newString = newString + "#{b}"
      j = j -1
      i = i - b.length
   end
  end
  puts newString
end

string = "1+2*3-20"
reverse_str(string)
string2 = "10-2*3-2000"
reverse_str(string2)

string3 = "10-2*3-+5-992000"
reverse_str(string3)

- ShariqueQA January 26, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverse_string(string):
    if "20" in string:
        array = ["02"]
        string = string.replace("20", "02")

    return string[::-1]


print(reverse_string("1 + 2 * 3 - 20"))

- Enthrayu January 27, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class String1 {
    public static void main(String[] args) {

        String1 s = new String1();
        String str = "1+2*3-20";
        String sa[] = str.split("");
        String ss = s.solution(sa);
        System.out.println(ss);
    }

    public String solution(String s[]){
        int l = s.length -1;
        String out="";
        int i=l;
        while(i> -1){
            String c = s[i];
            int j=0;
            if(!c.equals("+") || !c.equals("-") || !c.equals("*")){
                j=i;
            }
            while (j >0){
                String c1 = s[j];
                if(c1.equals("+") || c1.equals("-") || c1.equals("*")){
                    out = out + c1;
                    j = 0;
                }else{
                    out = c1 + out;
                    j--;
                }
                i--;
            }
        }
        return  out;
    }

}

- ss January 29, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class String1 {
public static void main(String[] args) {

String1 s = new String1();
String str = "1+2*3-20";
String sa[] = str.split("");
String ss = s.solution(sa);
System.out.println(ss);
}

public String solution(String s[]){
int l = s.length -1;
String out="";
int i=l;
while(i> -1){
String c = s[i];
int j=0;
if(!c.equals("+") || !c.equals("-") || !c.equals("*")){
j=i;
}
while (j >0){
String c1 = s[j];
if(c1.equals("+") || c1.equals("-") || c1.equals("*")){
out = out + c1;
j = 0;
}else{
out = c1 + out;
j--;
}
i--;
}
}
return out;
}
}

- ss January 29, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverseString(string):
temp = string[-2:]
length = len(string) -2
output = temp + string[5::-1]
print "{} is the actual string and {} is the outcome string".format(string, output)

if __name__ == '__main__':
reverseString("1+2*3-20")

- Dayananda D R February 11, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverseString(string):
    temp = string[-2:]
    length = len(string) -2
    output =  temp + string[5::-1]
    print "{} is the actual string and {} is the outcome string".format(string, output)

if __name__ == '__main__':
    reverseString("1+2*3-20")

- Dayananda D R February 11, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

var str = "1+2*3-20";
	str.split('').reverse().join('').replace(/02/gi, "20");

- Gopesh February 12, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def foo(st):
b='

'
c='

'
for i in st:

- Anonymous February 20, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is generic to keeping numbers as is and reversing on basis of operators.
1+2*3-20+5325/133

Ans : 133/5325+20-3*2+1

import java.util.ArrayList;
import java.util.HashSet;

public class ReverseStringsKeepNumberAsIs {
	HashSet<String> hs = new HashSet<String>();
	
	ReverseStringsKeepNumberAsIs(){
		this.hs.add("+");
		this.hs.add("-");
		this.hs.add("*");
		this.hs.add("/");
		this.hs.add("%");
		this.hs.add("^");
		this.hs.add("\\");
	}
	
	String reversalNumSame(String str) {
		// 1+2*3-20
		String[] brokenStr = (str+" ").split("");
		// can be used str+"".toCharArray()
                // Space is being used as a end of line character
		String result="",temp="";
		for (String c:brokenStr) {
			if ((this.hs.contains(c)) || (c.equalsIgnoreCase(" "))) {
				result = c + temp + result;
				temp="";
				c = "";
			}
			temp = temp + c;
		}
		return result.trim();
		
	}

- shubhamsrivastava007 February 22, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

// Javascript Implementation - 

/**
 * Reverse this string 1+2*3-20. Note: 20 must be retained as is. Expected
 * output: 20-3*2+1
 */


function reverseString(str) {
  let startIndex = 0;
  let stack = [];
  for(let i = 0, length = str.length; i < length; i++) {
    const char = str[i];
    if(isNaN(char)){
      let subStr = str.substring(startIndex, i);
      stack.push(subStr);
      stack.push(str[i]);
      startIndex = i+1;
    }
  }
  if(startIndex < str.length){
    let subStr = str.substring(startIndex);
    stack.push(subStr);
  }
  return stack.reverse().join('');
}

const str = "1+2*3-20+2000+";
console.log("Before Reverse String is -> " +  str);
const reverseStr = reverseString(str);
console.log("After  Reverse String is -> " +  reverseStr);

- Amit Bansal March 06, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

a = '221*3+1-23'

i = len(a) - 1
j = len(a) - 1

b = []

while i > 0:
if a[i] not in ('*', '+', '-', '/'):
i -= 1
else:
b.append(a[i + 1:j + 1])
b.append(a[i])
i -= 1
j = i

b.append(a[i:j + 1])

print(str(b))

- Anonymous March 31, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def reverse_arith_string(str_arith):
    '''
    Input Arithmetic operations and  numbers as strings and reverse the string
    without reversing values
    Time complexity = O(N) - Linearily Traversing in string
    Space complexity = O(N) - as storing the reversed string
    
    '''
    
    str_arith = str_arith.strip() 
    if str_arith == "" : return None
    
    d_sym={'+':0,'*':0,'-':0}
    str_arith_rev = ''
    end_pos = len(str_arith)

    for start_pos in range(len(str_arith)-1,-1,-1):
        if str_arith[start_pos] in d_sym : 
           str_arith_rev = str_arith_rev + str_arith[start_pos + 1:end_pos] + str_arith[start_pos]
           end_pos = start_pos
    str_arith_rev = str_arith_rev + str_arith[0:end_pos]

    return str_arith_rev

print(reverse_arith_string(" 1+2*3-20 "))
print(reverse_arith_string("1+2*3-204"))
print(reverse_arith_string("1+2*3-0"))
print(reverse_arith_string(""))

- Sri May 25, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class SplitRev 
{
	public static void main(String[] args) 
	{
		String s="1+2*3-204";
		String no[]=s.split("[^0-9]");
		String del[]=s.split("[0-9]");
		String tot[]=new String[no.length+del.length];
		int k=no.length-1,l=del.length-1;
		for(int i=0;i<tot.length;i++)
		{
			int j=i+1;
			if(!(j%2==0))
			{
				tot[i]=no[k];
				k--;
			}
			else
			{
				tot[i]=del[l];
				l--;
			}
		}
		String revSt="";
		for(String st: tot)
			revSt+=st;
		System.out.println(revSt);
	}

.

- Jai July 16, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

A very simple concept is to use a stack and push all the numeric values into it until we encounter an operator, if an operator is found concatenate all the numeric values to a string and pop out all the elements from the stack till it is empty, keep doing the same process until all characters in a string is traversed and finally concatenate the remaining numeric values to the string and return the string

Implementation:

#include<bits/stdc++.h>
using namespace std;
bool checkoperator(char c){
if(c == '-' || c == '+' || c == '/' || c == '*')
return true;
else
return false;
}
string reversestring(string str){
stack<char> s;
string st = "";
for(int i = str.length() - 1; i >= 0; i--){
if(checkoperator(str[i])){
while(!s.empty()){
st += s.top();
s.pop();
}
st += str[i];
}
else
s.push(str[i]);
}
while(!s.empty()){
st += s.top();
s.pop();
}
return st;
}
int main()
{
string str = "1+2*3-20456+980";
cout<<reversestring(str)<<endl;
return 0;
}

- swapnilkant11 May 28, 2019 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More