Amazon Interview Question for SDE1s


Country: United States
Interview Type: In-Person




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

geeksforgeeks.org/find-first-non-repeating-character-stream-characters/

Use hashmap to uniquely identify keys in place of repeated array.

- Nitin April 03, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

What is the point of using doubly linked list here? Can't we do the same thing by just using linked list?

- RavishSunnyRoshan April 17, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Created a Dictionary to hold key/value for elements that occur only once, with the value being their index in the list which we need to determine which one is the first occurrence. The hashtable holds the elements that occur more than once and we ignore those. Algo goes 1x through the list ignoring a string that is in the Hashtable (multiple) already, inserting into to the Dictionary (single) if not present, and moving from single to multiple if this is a first repeat. Result is Dictionary of unique elements whose values are their indexes. Loop through the resulting dictionary returning the key for the smallest value.

Since the hashtable and dictionary lookups are 0(1), I think this algo is 0(2n) where n is the number of elements in the list. Would happily except correction here if my big O performance assessment is wrong :)

protected string GetFirstUnique(List<string> baseList)
    {
        Dictionary<string,int> single = new Dictionary<string,int>();
        Hashtable multiple = new Hashtable();
        string retVal = null;
        int minIndex = int.MaxValue;

        for (int index = 0; index < baseList.Count; index++)
        {
            string str = baseList[index];
            if (!multiple.ContainsKey(str))
            {
                if (single.ContainsKey(str))
                {
                    single.Remove(str);
                    multiple.Add(str, 0);
                }
                else
                {
                    single.Add(str, index);
                }
            }
        }
        
        foreach (var e in single)
        {
            if (e.Value < minIndex)
                retVal = e.Key;
        }
        return retVal;
    }

- johny418 April 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

There is a sample of doing this with integers, and you xor all the values together, and it spits out the one unique value. If you could encode these to big integers, xor them all, and then reverse the encoding, the same concept would apply.

You could do this with a hashing function (say, CRC or MD5 for simplicity), but you'd need to maintain a table of hash->value. You'd have O(N) storage, and O(N) for processing (keeping elements in a hashtable)

Pseudocode:

sum = bigint()
map = hashmap()
for element in list:
	h = hash(element)
	map[h] = element
	sum ^= h

print map[sum]

- rotinom April 03, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Python has a built in library for this, collections.Counter.

def firstUnique(numbers):
	numCounts = collections.Counter(numbers)
	for x in numbers:
		if numCounts[x] == 1:
			return x
	return None

- Grendus April 03, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This u can do easily by using 2 data structure.
1)DLL which maintain the order in which letter is coming and
2) Hash with the letter,to remove the element from DLL which are repeating.

Give little bit thought its simple

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

>>> a=['a','b','c','b','a','d']
>>> b=list(set(a))
>>> for i in b:
...   count=0
...   for j in a:
...     if i==j:
...       count=count+1
...     if count==2:
...       break
...   if count==1:
...     print i
...
c
d

- Anonymous April 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

this is Python code

- Nishant April 19, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is a HashMap Based solution

public String findDuplicate(String[] inputStrings){
        Map<String,Integer> inputMap = new HashMap<>();
        int count;
        String uniqueString="";
        for(String input : inputStrings){
            if(inputMap.containsKey(input)){
                count = inputMap.get(input).intValue();
                count++;
                inputMap.put(input, count);
            }else{
                inputMap.put(input, 1);
            }
        }
        for(String input : inputStrings){
            if(inputMap.containsKey(input) && inputMap.get(input).intValue() ==1){
                uniqueString = input;
                break;
            }
        }
        return uniqueString;
    }

- Rudra April 29, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Use LinkedHashMap<String, Integer> , key will be string and integer will number of occurrences. Complexity will be O(n)

- om May 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Just traverse it in reverse order and save last uniq number (which is not in hashMap)

#!/usr/bin/perl

@list = (21, 2, 3, 4, 3, 21, 0, 1, 4);

foreach my $element (reverse @list)
{
if(not defined $hashMap{$element}) {
$first_uniq = $element;
$hashMap{$element} = 1;
}
}
print $first_uniq;

- Hamzah August 19, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

1. insert the stream of characters into hashset one by one
2. Before insertion, check the existence of the character stream
3. If already exists, remove the element from hashset
4. Print the first element of the hashset

- sasi March 29, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.collection2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UniqueElement {

	public static List<String> value;
	public static Map<String, Integer> MappedValues = new HashMap<String, Integer>();
	public static String uniqueval = null;
	public static String str = "";

	public UniqueElement() {
		value = new ArrayList<String>();
		value.add("BH");
		value.add("BH");
		value.add("F");
		value.add("AL");
		value.add("HJ");
		value.add("AL");
		value.add("HJ");
		value.add("PK");

		System.out.println(value);

	}

	protected String myVal(List<String> val) {

		for (int i = 0; i < val.size(); i++) {
			int count = 0;
			str = val.get(i);
			for (String key : val) {
				if (key == str) {
					count++;
					MappedValues.put(str, count);
					
				}
				MappedValues.put(str, count);
			}
		}

		for (String uniq : val) {
			if (MappedValues.containsKey(uniq)
					&& MappedValues.get(uniq).intValue() == 1) {
				uniqueval = uniq;
				break;
			}

		}
		return uniqueval;

	}

	public static void main(String[] args) {
		UniqueElement a = new UniqueElement();
		a.myVal(value);
		System.out.println(MappedValues);
		System.out.println(uniqueval);
	}

}

- Anonymous June 25, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Output:
[BH, BH, F, AL, HJ, AL, HJ, PK]
{HJ=2, BH=2, F=1, AL=2, PK=1}
F

- Anonymous June 25, 2015 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

I would do it in the following way....

Step 1: Iterate through all the elements in the list
Step 2: Insert each element in a set if its not there, else remove from the set.
Step 3: once end of list occurs, Iterate through the set and print if any element, else "print no unique element"

- madhur.eng April 04, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Well the person who down flagged it please be courteous enough to drop the reason for the same. Also this solution works as I have tried and tested it using JAVA

- madhur.eng April 19, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@Madhur do u think set can have duplicate into it?

Given a list with duplicate values find the first unique elements in it.
and From Ex : BH BH F AL HJ AL HJ PK
according to ur logic the O/P should be F PK

how u will decide which one is First Unique element?

- Vaibhavs April 19, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

The logic can be changed by just slightly to keep track of the first unique elemwnt added in set.... also I was under the impression that all the unique elements have to be printed.

- Madhur Mehta April 20, 2014 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

I need the first unique element
my solution is :

1. Insert the elements of the list into hashmap as Key and a count as value.
2. Before insert check the key into hashmap
if the key is present make the value as negative
else insert into the hashmap and increase the count value

3. After iterating the whole list,search for the key whose value is least +ve value
and that is the answer.

- Vaibhavs April 07, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

if it's an ASCII character set ... you could just make an array[256] and while iterating through the string array[charAt(i)]++ ... then iterate through the array to find the element with count = 1

- Anonymous April 02, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.


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