Amazon Interview Question
Developer Program EngineersCountry: India
Interview Type: Written Test
private static String removeTriplicate(StringBuilder input) {
int start = 0;
while (start < input.length() - 2) {
if (input.charAt(start) == input.charAt(start + 1) && input.charAt(start) == input.charAt(start + 2)) {
input.deleteCharAt(start);
input.deleteCharAt(start);
input.deleteCharAt(start);
start = 0;
} else {
start = start + 1;
}
}
return input.toString();
}
std::string RemoveThreeDups(const std::string& orig)
{
std::string str(orig);
std::string newStr;
bool foundDup = false;
do
{
foundDup = false;
newStr.clear();
for(int i = 0; i < str.size();)
{
if(i < (str.size() - 2) && str[i] == str[i + 1] && str[i] == str[i + 2])
{
i += 3;
foundDup = true;
}
else
{
newStr += str[i];
++i;
}
}
str = newStr;
} while(foundDup);
return newStr;
}
private static String removeTriplicate(StringBuilder input) {
int start = 0;
while (start < input.length() - 2) {
if (input.charAt(start) == input.charAt(start + 1) && input.charAt(start) == input.charAt(start + 2)) {
input.deleteCharAt(start);
input.deleteCharAt(start);
input.deleteCharAt(start);
start = 0;
} else {
start = start + 1;
}
}
return input.toString();
}
Simple solution using regex and Java's built-in Pattern and Matcher classes
public static void removeTriplicate(String input) {
Pattern consec3 = Pattern.compile("([a-z\\d])\\1\\1");
Matcher matcher = consec3.matcher(input);
String result = input;
while (matcher.find()) {
result = matcher.replaceFirst("");
matcher.reset(result);
}
System.out.println(result);
}
static string RemoveTriplicados(string original)
{
List<char> charList = original.ToCharArray().ToList();
for (int i = 0; i < charList.Count() - 2; i++)
if (charList[i] == charList[i + 1] && charList[i + 1] == charList[i + 2])
{
charList.RemoveAt(i + 2);
charList.RemoveAt(i + 1);
charList.RemoveAt(i);
i = -1;
}
return new string(charList.ToArray());
}
// remove 3 consecutive duplicates form a string
//i/p : aabbbaccddddc
//o/p : ccdc
StringBuilder testString = new StringBuilder("aabbbaccddddc");
int counter = 0;
for(int i = 0 ; i<testString.length()-2 && counter <= 2 ;)
{
char charAti = testString.charAt(i);
/*System.out.println(i + " : " + charAti + " "+
(i+1) + " : " + testString.charAt(i+1)+" " +
(i+2) + " : " + testString.charAt(i+2));*/
if(charAti == testString.charAt(i+1))
{
if(charAti == testString.charAt(i+2))
{
testString.delete(i, i+3);
// System.out.println("Deleting");
i=0;
counter++;
}
else
{
i=i+2;
}
}
else
{
i++;
}
}
System.out.println("The Output String is : "+testString);
// System.out.println("The final Counter is : " + counter);
}
public String removeTriplicate(String str) {
if (str == null || str.isEmpty() || str.length() < 3) {
return str;
}
char[] charArray = str.toCharArray();
int readIdx = 0;
int writeIdx = -1;
while (readIdx < charArray.length) {
if (readIdx < charArray.length - 2 && charArray[readIdx] == charArray[readIdx+1] && charArray[readIdx] == charArray[readIdx+2]) {
readIdx += 3;
} else {
charArray[++writeIdx] = charArray[readIdx++];
}
if (writeIdx > 1) {
if (charArray[writeIdx] == charArray[writeIdx-1] && charArray[writeIdx] == charArray[writeIdx-2]) {
writeIdx -=3;
}
}
}
if (writeIdx != -1) {
return new String(charArray, 0, writeIdx+1);
}
return new String();
}
This can be done using a simple stack
public static String removeTriplicate(String input)
{
char[] text=input.toCharArray();
char[] finalC;
String finalS;
Vector v=new Vector();
for(int i=0;i<text.length;i++)
{
v.add(text[i]);
if(v.size()>2)
{
Character topmost=(Character)v.get(v.size()-1);
Character secondtop=(Character)v.get(v.size()-2);
Character thirdtop=(Character)v.get(v.size()-3);
if(topmost.equals(secondtop) && topmost.equals(thirdtop))
{
v.remove(v.size()-1);
v.remove(v.size()-1);
v.remove(v.size()-1);
}
}
}
finalC=new char[v.size()];
for(int i=0;i<v.size();i++)
{
finalC[i]=((Character)v.get(i)).charValue();
}
finalS=String.copyValueOf(finalC);
return finalS;
}
public static String bomb(String input, int endIndex){
char[] ct = input.toCharArray();
for(int i=0; i<endIndex; i++){
int iter = i;
char temp = ct[i];
int counter = 0;
while(ct[iter] == temp){
iter++;
counter++;
}
if(counter >= 3){
for(int j = iter; j < endIndex; j++){
ct[j-3] = ct[j];
}
return bomb(new String(ct), endIndex-counter);
}
}
System.out.println("endindex :: "+ endIndex);
return (new String(ct)).substring(0, endIndex);
}
public static String bomb(String input, int endIndex){
char[] ct = input.toCharArray();
for(int i=0; i<endIndex; i++){
int iter = i;
char temp = ct[i];
int counter = 0;
while(ct[iter] == temp){
iter++;
counter++;
}
if(counter >= 3){
for(int j = iter; j < endIndex; j++){
ct[j-3] = ct[j];
}
return bomb(new String(ct), endIndex-counter);
}
}
System.out.println("endindex :: "+ endIndex);
return (new String(ct)).substring(0, endIndex);
}
public static String bomb(String input, int endIndex){
char[] ct = input.toCharArray();
for(int i=0; i<endIndex; i++){
int iter = i;
char temp = ct[i];
int counter = 0;
while(ct[iter] == temp){
iter++;
counter++;
}
if(counter >= 3){
for(int j = iter; j < endIndex; j++){
ct[j-3] = ct[j];
}
return bomb(new String(ct), endIndex-counter);
}
}
System.out.println("endindex :: "+ endIndex);
return (new String(ct)).substring(0, endIndex);
}
public static String bomb(String input, int endIndex){
char[] ct = input.toCharArray();
for(int i=0; i<endIndex; i++){
int iter = i;
char temp = ct[i];
int counter = 0;
while(ct[iter] == temp){
iter++;
counter++;
}
if(counter >= 3){
for(int j = iter; j < endIndex; j++){
ct[j-3] = ct[j];
}
return bomb(new String(ct), endIndex-counter);
}
}
System.out.println("endindex :: "+ endIndex);
return (new String(ct)).substring(0, endIndex);
}
Using stack.
Insert each char one by one into a stack. Before insert check the following:
If char to be inserted say C is same as top 2 elements(T1 and T2) of the stack. If so remove T1, T2 and don't insert C. If not insert C onto stack
Contents of stack gives the final string in reverse order.
You could also use a double linked list (or double ended queue) to avoid reversing at the end, at the cost of increased storage (due to additional pointers)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string in;
cin >> in;
vector<char> scratch;
int anchor = 0;
for (int i = 0; i < in.size(); ++i) {
scratch.push_back(in[i]);
if (scratch.size() > 2) {
const size_t sz = scratch.size();
if (scratch[sz - 1] == scratch[sz - 2] &&
scratch[sz - 2] == scratch[sz - 3]) {
scratch.resize(sz - 3);
}
}
}
for (int i = 0; i < scratch.size(); ++i) {
cout << scratch[i];
}
cout << endl;
return 0;
}
package practice.careercup;
import java.util.Stack;
public class Remove3ConsecuitiveDuplicates {
public static void main(String[] args) {
String input = "aabbbaccddddc";
Stack<CharacterCount> characterStack = new Stack<>();
for (Character eachChar : input.toCharArray()) {
if (!characterStack.isEmpty() &&
eachChar.equals(characterStack.peek().getCharacter()) ) {
CharacterCount characterCount = characterStack.peek();
if (characterCount.getCount() == 2 ){
characterStack.pop();
characterStack.pop();
} else {
characterStack.push(new CharacterCount(eachChar, characterCount.getCount()+1));
}
} else {
characterStack.push(new CharacterCount(eachChar, 1));
}
}
characterStack.forEach(characterCount -> System.out.print(characterCount.getCharacter()));
}
public static class CharacterCount {
private Character character;
private int count;
public CharacterCount(Character character, int count) {
this.character = character;
this.count = count;
}
public Character getCharacter() {
return character;
}
public int getCount() {
return count;
}
}
}
package com.gulshan;
import java.util.Scanner;
import java.util.Stack;
public class RemoveThreeConsecutiveDuplicatesFromStringClass {
@SuppressWarnings("resource")
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
String ip = null;
do {
System.out.println("Enter the eements..Enter "+ "\"-1\""+" to break");
ip = new Scanner(System.in).nextLine();
if (ip.equalsIgnoreCase("-1"))
continue;
stack.push(ip);
if (stack.size() >= 3) {
if ((stack.get(stack.size() - 1).equalsIgnoreCase(stack
.get(stack.size() - 2)))
&& ((stack.get(stack.size() - 2))
.equalsIgnoreCase(stack.get(stack.size() - 3)))) {
for (int i = 1; i <= 3; i++) {
stack.pop();
}
}
}
} while (!ip.equalsIgnoreCase("-1"));
System.out.println(stack);
}
}
package com.gulshan;
import java.util.Scanner;
import java.util.Stack;
public class RemoveThreeConsecutiveDuplicatesFromStringClass {
@SuppressWarnings("resource")
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
String ip = null;
do {
System.out.println("Enter the eements..Enter "+ "\"-1\""+" to break");
ip = new Scanner(System.in).nextLine();
if (ip.equalsIgnoreCase("-1"))
continue;
stack.push(ip);
if (stack.size() >= 3) {
if ((stack.get(stack.size() - 1).equalsIgnoreCase(stack
.get(stack.size() - 2)))
&& ((stack.get(stack.size() - 2))
.equalsIgnoreCase(stack.get(stack.size() - 3)))) {
for (int i = 1; i <= 3; i++) {
stack.pop();
}
}
}
} while (!ip.equalsIgnoreCase("-1"));
System.out.println(stack);
}
}
package com.gulshan;
import java.util.Scanner;
import java.util.Stack;
public class RemoveThreeConsecutiveDuplicatesFromStringClass {
@SuppressWarnings("resource")
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
String ip = null;
do {
System.out.println("Enter the eements..Enter "+ "\"-1\""+" to break");
ip = new Scanner(System.in).nextLine();
if (ip.equalsIgnoreCase("-1"))
continue;
stack.push(ip);
if (stack.size() >= 3) {
if ((stack.get(stack.size() - 1).equalsIgnoreCase(stack
.get(stack.size() - 2)))
&& ((stack.get(stack.size() - 2))
.equalsIgnoreCase(stack.get(stack.size() - 3)))) {
for (int i = 1; i <= 3; i++) {
stack.pop();
}
}
}
} while (!ip.equalsIgnoreCase("-1"));
System.out.println(stack);
}
}
public class removeconsecutive3strings {
public static void main(String[] args) {
ShortenString("bbbbaccdddddddc","",0,1);
}
public static void ShortenString(String s,String ans,int index,int count) {
if(count >=3){
ans=ans.substring(0,ans.length()-3);
}
if(index == s.length()){
System.out.println(ans);
return;
}
if(ans.length()!=0 && s.charAt(index) == ans.charAt(ans.length()-1)){
ShortenString(s,ans +(s.charAt(index)),index+1,count+1);
}else{
ShortenString(s,ans +(s.charAt(index)),index+1,1);
}
}
}
public class removeconsecutive3strings {
public static void main(String[] args) {
// TODO Auto-generated method stub
// String s ="aabbbccddddc";
// System.out.println(s.substring(0, 8));
//StringBuilder s = new StringBuilder();
ShortenString("bbbbaccdddddddc","",0,1);
}
public static void ShortenString(String s,String ans,int index,int count) {
//System.out.println(ans.length());
if(count >=3){
ans=ans.substring(0,ans.length()-3);
//System.out.println(ans);
}
if(index == s.length()){
System.out.println(ans);
return;
}
if(ans.length()!=0 && s.charAt(index) == ans.charAt(ans.length()-1)){
ShortenString(s,ans +(s.charAt(index)),index+1,count+1);
}else{
ShortenString(s,ans +(s.charAt(index)),index+1,1);
}
}
}
import java.util.Scanner;
public class Sample {
public static void main(String ar[]) {
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
String str;
String[] arr = new String[len];
for (int i = 0; i < len; i++) {
str = sc.next();
arr[i] = "";
String temp = str;
for (int j = 0; j < (temp.length() - 3);) {
if (temp.charAt(j) == temp.charAt(j + 1) && temp.charAt(j) == temp.charAt(j + 2)) {
temp = temp.substring(0, j) + "" + temp.substring(j + 3);
j = j + 3;
} else {
arr[i] = arr[i] + temp.charAt(j);
j = j + 1;
}
}
if (temp.length() > 2) {
if (arr[i].length() != 0) {
if (!(str.charAt(str.length() - 3) == str.charAt(str.length() - 2)) || !(str.charAt(str.length() - 3) == str.charAt(str.length() - 1))) {
if (!(str.charAt(str.length() - 3) == str.charAt(str.length() - 5)) || !(str.charAt(str.length() - 3) == str.charAt(str.length() - 4))) {
arr[i] = arr[i] + str.charAt(str.length() - 3) + str.charAt(str.length() - 2) + str.charAt(str.length() - 1);
} else {
arr[i] = arr[i] + str.charAt(str.length() - 2) + str.charAt(str.length() - 1);
}
}
}
} else {
arr[i] = temp;
}
if (arr[i].length() == 0) {
System.out.println("-1");
} else {
System.out.println(arr[i]);
}
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.apache.log4j;
import java.util.Scanner;
public class Sample {
public static void main(String ar[]) {
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
String str;
String[] arr = new String[len];
for (int i = 0; i < len; i++) {
str = sc.next();
arr[i] = "";
String temp = str;
for (int j = 0; j < (temp.length() - 3);) {
if (temp.charAt(j) == temp.charAt(j + 1) && temp.charAt(j) == temp.charAt(j + 2)) {
temp = temp.substring(0, j) + "" + temp.substring(j + 3);
j = j + 3;
} else {
arr[i] = arr[i] + temp.charAt(j);
j = j + 1;
}
}
if (temp.length() > 2) {
if (arr[i].length() != 0) {
if (!(str.charAt(str.length() - 3) == str.charAt(str.length() - 2)) || !(str.charAt(str.length() - 3) == str.charAt(str.length() - 1))) {
if (!(str.charAt(str.length() - 3) == str.charAt(str.length() - 5)) || !(str.charAt(str.length() - 3) == str.charAt(str.length() - 4))) {
arr[i] = arr[i] + str.charAt(str.length() - 3) + str.charAt(str.length() - 2) + str.charAt(str.length() - 1);
} else {
arr[i] = arr[i] + str.charAt(str.length() - 2) + str.charAt(str.length() - 1);
}
}
}
} else {
arr[i] = temp;
}
if (arr[i].length() == 0) {
System.out.println("-1");
} else {
System.out.println(arr[i]);
}
}
}
}
import java.util.Scanner;
public class Sample {
public static void main(String ar[]) {
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
String str;
String[] arr = new String[len];
for (int i = 0; i < len; i++) {
str = sc.next();
arr[i] = "";
String temp = str;
for (int j = 0; j < (temp.length() - 3);) {
if (temp.charAt(j) == temp.charAt(j + 1) && temp.charAt(j) == temp.charAt(j + 2)) {
temp = temp.substring(0, j) + "" + temp.substring(j + 3);
j = j + 3;
} else {
arr[i] = arr[i] + temp.charAt(j);
j = j + 1;
}
}
if (temp.length() > 2) {
if (arr[i].length() != 0) {
if (!(str.charAt(str.length() - 3) == str.charAt(str.length() - 2)) || !(str.charAt(str.length() - 3) == str.charAt(str.length() - 1))) {
if (!(str.charAt(str.length() - 3) == str.charAt(str.length() - 5)) || !(str.charAt(str.length() - 3) == str.charAt(str.length() - 4))) {
arr[i] = arr[i] + str.charAt(str.length() - 3) + str.charAt(str.length() - 2) + str.charAt(str.length() - 1);
} else {
arr[i] = arr[i] + str.charAt(str.length() - 2) + str.charAt(str.length() - 1);
}
}
}
} else {
arr[i] = temp;
}
if (arr[i].length() == 0) {
System.out.println("-1");
} else {
System.out.println(arr[i]);
}
}
}
}
public string RemoveThreeDuplicates(string s)
{
if (string.IsNullOrEmpty(s))
return s;
int length = s.Length;
var arr = s.ToArray();
int oldLength = 0;
while (length != oldLength)
{
int j = 0;
for (int i=0; i < length; i++)
{
if ((i + 2) < length && arr[i] == arr[i+1] && arr[i] == arr[i+2])
i+=2; // We need to increment 3, the for-loop add the missing one
else
{
arr[j] = arr[i];
j++;
}
}
oldLength = length;
length = j;
}
var sb = new StringBuilder();
for (int i=0; i < length; i++)
sb.Append(arr[i]);
return sb.ToString();
}
Shouldn't the sample output be 'ccdc' if the question is correct?
- Mayank January 21, 2017