Amazon Interview Question for Software Engineer / Developers


Team: payments team
Country: India
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
0
of 6 vote

XOR the characters - as you read the string. when it's non-zero - that's the first non repeating character.

- gabhijit November 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

wondering why down voted. You should be nice enough to point the error if you down vote it. Or better still, post the question more appropriately!

- gabhijit November 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

How u will get the result by xoring all the character.
Try this one
abdcccbd
u will not get right character.

- Aalok November 06, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

This is where a question is not clear to me ---

in a string aaaabccdddd - b is the first non-repeating character
in a string abaaaaaaabb - b isthe first non-repeating character.

The question was not quite clear. My solution assumes the above is the question.. you've to remember first and keep xoring with that.

- gabhijit November 06, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 vote

you can just count the num of occurrences of each character. then
scan the first 26 characters of the arrray for value.
O(n), no temporary space.

- Anonymous November 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Provided you're dealing with an English string. Have you considered a string in Chinese?

- Chris November 05, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@ Anonymous: are u considering the first non-repeating character ?
U are just saying the first non-repeating character in alphabets. I think, the question is about first non-repeating character in string.
Ex: aacdcb --> ans : 'd' not 'b'.

- bharat November 23, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 2 vote

Have a map<char, int>. Have a timestamp value initialised to 0. Loop through the string, incrementing timestamp at each step. Assign value of current timestamp to map[string[i]]. Once done through the loop, you need a linear search for getting the minimum timestamp value, which is your answer. O(n) time, O(n) space.

- Unos November 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Change the count array to a map of <char, int> and this works.

- Giana September 02, 2019 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

public static char firtNonRepeatingCharCaseSensitive(char[] s) {
int[] counts = new int[256]; // uses buffer
for (char c : s) {
counts[c]++;
}

for (int i = 0; i < s.length; i++) {
if (counts[s[i]] == 1)
return s[i];
}

return Character.UNASSIGNED // anything that indicates no character found;
}

Complexity: O(n)

- Anonymous November 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

For "mansi" string it is giving wrong answer

- Mansi February 25, 2020 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

String S = "ababcc";
		HashMap<Character, Integer> map = new HashMap<Character, Integer>();
		for (int c = 0; c < S.length(); c++) {
			if (null != map.get(S.charAt(c))) {
				System.out.println("First Char=" + S.charAt(c));
				break;
			} else {
				map.put(S.charAt(c), 0);
			}
		}

- Naveen November 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

# include<stdio.h>

int main()

{

char str[10];

printf("\n enter the string:");
scanf("%s", str);

sort(str);

printf("\n sorted %s", str);

firstnonrepeat(str);

}

void sort(char *str)
{

int i,len,j;
char temp;

len=strlen(str);

for(i=0;i<len;i++)
{

for(j=i;j>0;j--)
{
if(str[j]<str[j-1])
{
temp=str[j-1];
str[j-1]=str[j];
str[j]=temp;
}

}

- Gaurav November 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

void firstnonrepeat(char *str)
{

int i,j;
int flag=0;

for(i=0;i<strlen(str);i++)
{

if(str[i]!=str[i+1] && str[i]!=str[i-1])

{
printf("\n first non repeated charater is %c", str[i]);

return;

}

}

- Gaurav November 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Maintain a HashMap that tracks if a character has been seen once, or more than once. Loop over the string once, and if the char has the seen once value in the hashmap then set its value to seen twice. Then loop through the string again and return the first character whose value in the hashmap is seen once.

import java.util.*;

class firstNonRepeated {

	public static void main(String []args){
		HashMap charHash = new HashMap();
		int i, length;
		char c;
		Object seenOnce = new Object();
		Object seenTwice = new Object();

		if(args.length == 1){
			String input = args[0];

			length = input.length();

			for(i=0;i<length;i++){
				c = input.charAt(i);
				Object o = charHash.get(c);
				if( o == null ){
					charHash.put( c, seenOnce );
				} else if( o == seenOnce ){
					charHash.put( c, seenTwice );
				}
			}

			for(i=0;i<length;i++){
				c = input.charAt(i);
				if( charHash.get(c) == seenOnce ){
					System.out.println(c);
					return;
				}
			}
			System.out.println("All letters are repeated");
		} else {
			System.out.println("Incorrect Arguments. Requires one string.");
		}
	}

}

- paj November 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Two possible solutions:

1. If string contains only ASCII characters. [0 ... 255 ]
2. String contains not only ASCII characters.

1.

public static char firstNonRepeatedCharAscii(String str){
		checkForNull(str);
		
		int[] charsCountArr = new int[ASCII_MAX_CODE + 1];
		
		int strLength = str.length();
		char ch;
		
		for( int i =0; i < strLength; i++ ){
			ch = str.charAt(i);
			++charsCountArr[ch];
		}
		
		for( int i =0; i < strLength; i++ ){
			ch = str.charAt(i);
			if( charsCountArr[ch] == 1 ){
				return ch;
			}
		}
		
		return EMPTY_CHARACTER;
	}

2.

public static char firstNonRepeatedChar(String str){
		checkForNull( str );		
		Map<Character, Integer> charsCount = new HashMap<Character, Integer>();
		
		int strLength = str.length();
		char ch;
		
		for( int i =0; i < strLength; i++ ){
			ch = str.charAt(i);
			
			int code = ch;
			
			if( code >=0 && code <= 255 ){
				
			}
			
			Integer curChCount = charsCount.get(ch);
			
			if( curChCount == null ){
				curChCount = Integer.valueOf(1);
			}
			else {
				++curChCount;
			}
			
			charsCount.put( ch, curChCount );			
		}
		
		for( int i =0; i < strLength; i++ ){
			ch = str.charAt(i);
			
			if( charsCount.get(ch) == 1 ){
				return ch;
			}
		}
		
		return EMPTY_CHARACTER;
	}

- m@}{ November 05, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class FirstNonRepeat {	
	public static void main(String[] args) {
		String str = "hhhelloworld";
		int[] allChars = new int[256];
		for(int i=0;i < str.length(); i++) {
		    allChars[(int)str.charAt(i)]++;
		}
		
		StringBuilder sb = new StringBuilder(str);
		for(int i=0; i< sb.length(); i++) {
			if(allChars[(int)sb.charAt(i)] > 1) {
				sb.deleteCharAt(i);
				i--;
			}
		}
		
		System.out.println("First non repeating char: " + sb.charAt(0));
	}
}

- sparrowman November 06, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

char findFirstNonRepeatingCharInaString(char* arr, int size) {
	int a[256] = {0};
	int c = 0;
	int min = -1;
	for (int i = 0; i < size; i++) {
		c = arr[i];
		//if repeated then make it negative
		if (a[c] > 0)
			a[c] = -1;
		//store the index instead of the number of occurences
		else if (a[c] == 0)
			a[c] = i;
		else {
		}
	}
	//find the minimum index in the array
	
	for (int i = 0; i < 256; i++) {
		if (a[i] > 0 && a[i] < min)
			min = a[i];
	}
	if (min >= 0)
		return arr[min];
	else
		return 0;
}

- praveen November 09, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

The first non-repeating character in the string will be returned.

- praveen November 09, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Below is the code to fidn out first non repeating character in a given string :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{

char *str="aabbbccccddeffffgg";
char non_repeat;
bool nr=false;
int len=strlen(str);
int i=0,j;
for(i=0;i<len;i++)
{
        non_repeat=str[i];
        nr=true;
        for(j=0;j<len;j++)
        {
        if(i!=j)
        {
            if(str[i]==str[j])
                {
                nr=false; 
                break;
                }
        }
        }

if(nr==true) // first non repeating character found
break;
}
if(nr)
printf("The non repeated character is %c\n", non_repeat);
else
printf("There are no non repeated characters in the string\n");

return 0;
}

- Pallavi July 15, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{

char *str="aabbbccccddeffffgg";
char non_repeat;
bool nr=false;
int len=strlen(str);
int i=0,j;
for(i=0;i<len;i++)
{
        non_repeat=str[i];
        nr=true;
        for(j=0;j<len;j++)
        {
        if(i!=j)
        {
            if(str[i]==str[j])
                {
                nr=false;
                break;
                }
        }
        }

if(nr==true) // first non repeating character found
break;
}
if(nr)
printf("The non repeated character is %c\n", non_repeat);
else
printf("There are no non repeated characters in the string\n");

return 0;
}

- Pallavi July 15, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{

char *str="aabbbccccddeffffgg";
char non_repeat;
bool nr=false;
int len=strlen(str);
int i=0,j;
for(i=0;i<len;i++)
{
non_repeat=str[i];
nr=true;
for(j=0;j<len;j++)
{
if(i!=j)
{
if(str[i]==str[j])
{
nr=false;
break;
}
}
}

if(nr==true)
break;
}
if(nr)
printf("The non repeated character is %c\n", non_repeat);
else
printf("There are no non repeated characters in the string\n");

return 0;
}

- Anonymous July 15, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{

char *str="aabbbccccddeffffgg";
char non_repeat;
bool nr=false;
int len=strlen(str);
int i=0,j;
for(i=0;i<len;i++)
{
        non_repeat=str[i];
        nr=true;
        for(j=0;j<len;j++)
        {
        if(i!=j)
        {
            if(str[i]==str[j])
                {
                nr=false;
                break;
                }
        }
        }

if(nr==true)
break;
}
if(nr)
printf("The non repeated character is %c\n", non_repeat);
else
printf("There are no non repeated characters in the string\n");

return 0;
}

- Pallavi July 15, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class FirstNonRepeatedCharacterEfficient {
    public static void main(String [] args){
        CharCountAndPosition [] array=new CharCountAndPosition[256];
        for(int i=0;i<256;i++)
        {
            array[i]=new CharCountAndPosition();
        }
        Scanner scan=new Scanner(System.in);
        String str=scan.next();
        int len=str.length();
        for(int i=0;i<len;i++){
            char c=str.charAt(i);
            int index=c-'a';            
            int frequency=array[index].frequencyOfchar;
            if(frequency==0)
                array[index].firstIndex=i;
            array[index].frequencyOfchar=frequency+1;    
            //System.out.println(c+" "+array[index].frequencyOfchar);
        }
        boolean flag=false;
        int firstPosition=Integer.MAX_VALUE;
        for(int i=0;i<256;i++){            
            if(array[i].frequencyOfchar==1){
                //System.out.println("character="+(char)(i+(int)'a'));
                if(firstPosition> array[i].firstIndex){                    
                    firstPosition=array[i].firstIndex;
                    flag=true;
                }
            }            
        }
        if(flag==true)
            System.out.println(str.charAt(firstPosition));
        else
            System.out.println("There is no such type of character");
    } 
}
class CharCountAndPosition{
    int firstIndex;
    int frequencyOfchar;

}

- neelabhsingh November 05, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class FirstNonRepeatedCharacterEfficient {
public static void main(String [] args){
CharCountAndPosition [] array=new CharCountAndPosition[256];
for(int i=0;i<256;i++)
{
array[i]=new CharCountAndPosition();
}
Scanner scan=new Scanner(System.in);
String str=scan.next();
int len=str.length();
for(int i=0;i<len;i++){
char c=str.charAt(i);
int index=c-'a';
int frequency=array[index].frequencyOfchar;
if(frequency==0)
array[index].firstIndex=i;
array[index].frequencyOfchar=frequency+1;
//System.out.println(c+" "+array[index].frequencyOfchar);
}
boolean flag=false;
int firstPosition=Integer.MAX_VALUE;
for(int i=0;i<256;i++){
if(array[i].frequencyOfchar==1){
//System.out.println("character="+(char)(i+(int)'a'));
if(firstPosition> array[i].firstIndex){
firstPosition=array[i].firstIndex;
flag=true;
}
}
}
if(flag==true)
System.out.println(str.charAt(firstPosition));
else
System.out.println("There is no such type of character");
}
}
class CharCountAndPosition{
int firstIndex;
int frequencyOfchar;
}

- neelabhsingh November 05, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class FirstNonRepeatedCharacterEfficient {
    public static void main(String [] args){
        CharCountAndPosition [] array=new CharCountAndPosition[256];
        for(int i=0;i<256;i++)
        {
            array[i]=new CharCountAndPosition();
        }
        Scanner scan=new Scanner(System.in);
        String str=scan.next();
        int len=str.length();
        for(int i=0;i<len;i++){
            char c=str.charAt(i);
            int index=c-'a';            
            int frequency=array[index].frequencyOfchar;
            if(frequency==0)
                array[index].firstIndex=i;
            array[index].frequencyOfchar=frequency+1;    
            //System.out.println(c+" "+array[index].frequencyOfchar);
        }
        boolean flag=false;
        int firstPosition=Integer.MAX_VALUE;
        for(int i=0;i<256;i++){            
            if(array[i].frequencyOfchar==1){
                //System.out.println("character="+(char)(i+(int)'a'));
                if(firstPosition> array[i].firstIndex){                    
                    firstPosition=array[i].firstIndex;
                    flag=true;
                }
            }            
        }
        if(flag==true)
            System.out.println(str.charAt(firstPosition));
        else
            System.out.println("There is no such type of character");
    } 
}
class CharCountAndPosition{
    int firstIndex;
    int frequencyOfchar;

}

- neelabhsingh November 05, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class FirstRepeatingAndNonRepeatingElements {

	/**
	 * 
	 * @param elements
	 * @return
	 */
	private int firstRepeatedElement(int[] elements) {
		int firstRepeatedElement = -1;
		if(elements!=null && elements.length>0) {
			Set<Integer> setOfElements = new HashSet<>();
			for(int i=elements.length-1;i>=0;i--){
				if(setOfElements.contains(elements[i])) {
					firstRepeatedElement = elements[i];
				} else {
					setOfElements.add(elements[i]);
				}
			}
		}
		return firstRepeatedElement;
	}
	
	
	private int  firstNonRepeatedHashSet(int [] elements)  {
		int firstNonRepatedElement = -1;
		Set<Integer> hashOfElements = new HashSet<>();
		if(elements!=null && elements.length>0) {
			for(int i=elements.length-1;i>=0;i--) {
				if(!hashOfElements.contains(elements[i])) {
					hashOfElements.add(elements[i]);
					firstNonRepatedElement = elements[i];
				}
			}
		}
		return firstNonRepatedElement;
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		FirstRepeatingAndNonRepeatingElements firstNonRepeatingElement = 
				new FirstRepeatingAndNonRepeatingElements();
		int[] input = new int[]{1,5,3,4,3,5,6,1};
		
		int firstRepeatedElement = firstNonRepeatingElement.
				firstRepeatedElement(input);
		
		System.out.println(" The First  Repating Element is "
				+ firstRepeatedElement);
		
		
		int firstNonRepeatedElement = firstNonRepeatingElement.
				firstNonRepeatedHashSet(input);
		
		System.out.println(" The First Non Repating Element is "
				+ firstNonRepeatedElement);

	}

- kanaparthikiran April 08, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

public class FirstRepeatingAndNonRepeatingElements {

	/**
	 * 
	 * @param elements
	 * @return
	 */
	private int firstRepeatedElement(int[] elements) {
		int firstRepeatedElement = -1;
		if(elements!=null && elements.length>0) {
			Set<Integer> setOfElements = new HashSet<>();
			for(int i=elements.length-1;i>=0;i--){
				if(setOfElements.contains(elements[i])) {
					firstRepeatedElement = elements[i];
				} else {
					setOfElements.add(elements[i]);
				}
			}
		}
		return firstRepeatedElement;
	}
	
	
	private int  firstNonRepeatedHashSet(int [] elements)  {
		int firstNonRepatedElement = -1;
		Set<Integer> hashOfElements = new HashSet<>();
		if(elements!=null && elements.length>0) {
			for(int i=elements.length-1;i>=0;i--) {
				if(!hashOfElements.contains(elements[i])) {
					hashOfElements.add(elements[i]);
					firstNonRepatedElement = elements[i];
				}
			}
		}
		return firstNonRepatedElement;
	}
	
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		FirstRepeatingAndNonRepeatingElements firstNonRepeatingElement = 
				new FirstRepeatingAndNonRepeatingElements();
		int[] input = new int[]{1,5,3,4,3,5,6,1};
		
		int firstRepeatedElement = firstNonRepeatingElement.
				firstRepeatedElement(input);
		
		System.out.println(" The First  Repating Element is "
				+ firstRepeatedElement);
		
		
		int firstNonRepeatedElement = firstNonRepeatingElement.
				firstNonRepeatedHashSet(input);
		
		System.out.println(" The First Non Repating Element is "
				+ firstNonRepeatedElement);

	}

- kanaparthikiran April 08, 2018 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

sol-1: Sort the string as an array based on ascii code. Next, do a linear scan.
Time complexity=O(n)

sol-2: Use a LinkedHashtable and maintain a occurrence-count for every character. At the end, again scan thru the hashtable to find an entry with count as 1. As soon as u find, print and exit.
TimeComplexity=O(n). SpaceComplexity=O(n)

- Ashok November 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Your algorithms wont return first non repeating character. They'll just return non repeating character

- A November 04, 2012 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

public static char firtNonRepeatingCharCaseSensitive(char[] s) {
		int[] counts = new int[256];
		for (char c : s) {
			counts[c]++;
		}

		for (int i = 0; i < s.length; i++) {
			if (counts[s[i]] == 1)
				return s[i];
		}

		return Character.UNASSIGNED;
	}

Used extra space and Complexity : O(n)

- AP November 04, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

How do you ensure the element returned is FIRST nonreapeated.I think u are returning non repeated char with smallest char value

- kaur November 25, 2012 | Flag


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