Amazon Interview Question for Developer Program Engineers


Country: India
Interview Type: Written Test




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

Shouldn't the sample output be 'ccdc' if the question is correct?

- Mayank January 21, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

def remove_triplicate(string):
    res = ""
    i = 0
    while i < len(string):
        if i < len(string) - 2 and string[i]*3 == string[i:i+3]:
            i += 3
        else:
            res += string[i]
            i += 1
            
    if len(res) == len(string):
        return res
    else:
        return remove_triplicate(res)
    

print remove_triplicate("aabbbacdddcccdcccdcc")

- Nitish Garg January 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

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();
	}

- gaurs January 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This needs a little bit more detail...what is a `3 consecutive duplicate`?

- srterpe January 17, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
}

- Surya January 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();
	}

- root January 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Could you please elaborate the question. Are we supposed to remove only the triplets or any kind of duplicate elements whether they are double, triple or quadriple ?

- snakeonbasket January 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);

    }

- Sean January 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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());
        }

- LS January 19, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

what does i=-1 does here

- ajay June 29, 2021 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

// 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);
	}

- Swaroop January 20, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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();
    }

- slvrhwk January 25, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
}

- Gaurav Tak January 25, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
}

- SandeepSahu January 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
	}

- SandeepSahu January 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);

}

- SandeepSahu January 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);

}

- sandeepsahu January 28, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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)

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

#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;
}

- Naughty February 04, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

def RemoveConsecutiveChars(mystring):
    for i in range(len(mystring)-2):
        if mystring[i] == mystring[i+1] == mystring[i+2]:
            mystring= mystring.replace(mystring[i:i+3],"")
            return RemoveConsecutiveChars(mystring)
    return mystring
print RemoveConsecutiveChars("aabbbaccddddc") #Returns ccdc

- ankitpatel2100 February 27, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
        }
        
    }

}

- binitbhas May 01, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
	}
}

- Gulshan May 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
	}
}

- Gulshan May 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
	}
}

- Gulshan Kumar May 08, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
}
}
}

- Raghav June 21, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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);
		}
	}
}

- raghavg06 June 21, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

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]);
}
}
}
}

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

/*
* 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]);
}
}
}
}

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

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]);
}
}
}
}

- Dinesh March 27, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

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();
}

- hnatsu January 18, 2017 | 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