Amazon Interview Question for Software Engineer / Developers


Country: India
Interview Type: In-Person




Comment hidden because of low score. Click to expand.
2
of 4 vote

Here is my answer for this question:

basicalgos.blogspot.com/2012/04/38-find-substr-based-on-map.html

- Andy April 01, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Correct me if I'm wrong but your solution returns the fisrt substring but not the substring with the minimum lenght. I.e.,
input: target - abbcda, hash - acd
your output: abbcd
desired output: cda

- Aleksey.M January 29, 2013 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

Nope, the algo is correct, it cannot return "abbcd", as as soon as you process 'b', the value of its mapping in the hashmap will reduce below zero and you will discard this substring.

- amritaansh123 February 12, 2013 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

just a variation of find minimum window which contains all characters ofa string

- richa.shrma.iitd April 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

We can create a suffix tree and and only search for those suffices that start from the characters given in the HashMap and then find the minimum.

- Free Bird April 09, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think we can build an inverted list with positions from the raw string just with the keys from map, and check weather the inverted list has successive positions or not.

If this methods makes sense to anyone, please let me know.

- milo April 13, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

How you will take into account the characters which can occur multiple times?

- Indy May 25, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is the best algo which is O(N) time complexity:
http (double dot) //leetcode (dot) com/2010/11/finding-minimum-window-in-s-which (dot) html

- Aleksey.M January 29, 2013 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

O(n) time Complexity

public class findSubstingSyncWithmap {

  /**
   * @param args
   */
  public static void main(String[] args) {
    String s="acbadrbdady";
    Map m = new HashMap();
    boolean done=false;
    m.put('b', 1);
    m.put('a', 1);
    m.put('d', 2);
    int si=0;
    Set<Character> set = new HashSet<Character>();
    set=m.keySet();
    Map<Character,Integer> mcopy = new HashMap<Character,Integer>();
    mcopy.putAll(m);
   for(int i=0;i<s.length();i++){
     if(set.contains(s.charAt(i))){
       if(done==false)
         si=i;
       done=true;
       int k=(int)mcopy.get(s.charAt(i));
       mcopy.put(s.charAt(i), k-1);
     }
     else{
       Iterator<Integer> it = mcopy.values().iterator();
       while(it.hasNext()){
         if(it.next()!=0){
           done=false;
           mcopy.clear();
           mcopy.putAll(m);
           break;
         }
       }
       if(done==true){
         System.out.println("I have got the substring which is "+s.substring(si, i));
       }
     }
   }
  }
}

- razik.islam February 01, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

find all the permutations of the alphabets and then we can use the KMP algorithm to match the string.

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

It will fail in many situations.It's not necessary to have the sub string of exactelly same size. In many cases the substring may contain other character that we have in map.

- neel April 02, 2012 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Keep a queue of characters which you have found till now in the text which are in the map as well. While queuing, decrease the count in the map, while dequeuing increase the count in the map.

Here is when we queue and dequeue:

Queue Q
foreach character in text
if map[character] > 0
Q.Enqueue[character]; map[character]--;
if (Q.size == requiredLength) return Q.ToString();
else
while(Q.front() != character)
map[Q.Dequeue]++;
Q.Dequeue; Q.Enqueue[character];

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

I don't think it will find a substring. just try running it on the sample case. May be I am missing something here, the code is not well formed, hence difficult to understand.

- Indy May 25, 2012 | Flag
Comment hidden because of low score. Click to expand.
-1
of 1 vote

I think I can solve it in O(n) with just comparisons:

So let's use an array of integers as indices such that int arrayIndex[hash.size] = 0. Now iterate along the array and start dropping each index where the array[arrayIndex[index]] is stored in the array. When we find a match, decrement the hash value associated with count and increment index.

If at any point the hash count falls below 0 then set arrayIndex[0] = arrayIndex[index]. We do this to in a way, move the pointer up to the current pointer.

If everything in the hash equals zero then we have a POSSIBLE solution, so calculate the difference between arrayIndex[0] and arrayIndex[n] and compare to the minCount and store arrayIndex[0] as left and arrayIndex[n] as right.

If index == n and arrayIndex[index] < str.length() then we bring the far left pointer up to the front, hash what it's pointing at, increment the count in the hash table and repeat the steps... it's almost like circular pointers...

This is to take care of cases like aaretbda where the first iteration would have pointers at [1]. [5], and [6].... but then would take [1] with 'a' and re-hash it then have that pointer point at [7]...

I know this sounds really confusing but let me know if it makes sense to anyone.

- rdo April 12, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
-1
of 1 vote

Here is the code for the given problem (C# console app):

class Program
{
static void Main(string[] args)
{
Dictionary<char, int> hashMap = new Dictionary<char, int>();
hashMap.Add('b', 1);
hashMap.Add('d', 1);
hashMap.Add('a', 1);

string parentString = "abcrefbada";
string substring = string.Empty;
if (parentString.GetSpecialSubstring(hashMap, out substring))
{
Log.Comment("Found substring is: " + substring);
}
else
{
Log.Comment("Special substring NOT FOUND!");
}
}
}

static class StringExtensions
{
public static bool GetSpecialSubstring(this string parentString, Dictionary<char, int> hashMap, out string specialSubstring)
{
specialSubstring = string.Empty;

#region Error Checking
//// DO ERROR CHECKING HERE...
if (string.IsNullOrEmpty(parentString))
{
Log.Comment("parent substring cannot be Null or empty.");
return false;
}

if (hashMap == null || hashMap.Count == 0)
{
Log.Comment("hashMap cannot be Null or empty.");
return false;
}

if (parentString.Length < hashMap.Count)
{
Log.Comment("parent string cannot be less than no of characters in hashMap.");
return false;
}

int hashMapCharCount = 0;
foreach (char hashMapChar in hashMap.Keys)
{
int charCount = hashMap[hashMapChar];
if (charCount < 0)
{
Log.Comment("Character count on a hashmap cannot be less than 0.");
return false;
}

hashMapCharCount += charCount;
}

if (parentString.Length < hashMapCharCount)
{
Log.Comment("parent string cannot be less than no of characters in hashMap.");
return false;
}
#endregion

//// START PROCESSING HERE.
Dictionary<char, int> localHashMap = new Dictionary<char, int>(hashMap);

int parentStringProcessingCounter = 0;
bool specialSubstringFound = false;
while (!specialSubstringFound && parentStringProcessingCounter <= (parentString.Length - hashMapCharCount))
{
//parentString[parentStringProcessingCounter]
int count = -1;
if (hashMap.TryGetValue(parentString[parentStringProcessingCounter], out count))
{
//Check if substring exists this character onwards.
specialSubstringFound = isSpecialStringFoundAtIterator(parentString, parentStringProcessingCounter, localHashMap, hashMapCharCount, out specialSubstring);
localHashMap = new Dictionary<char, int>(hashMap);
}

parentStringProcessingCounter++;
}

return specialSubstringFound;
}

private static bool isSpecialStringFoundAtIterator(string parentString, int parentIterator, Dictionary<char, int> hashMap, int hashMapCharCount, out string specialSubstring)
{
specialSubstring = string.Empty;
bool isSpecialSubstringFound = true;

if (parentString.Length - parentIterator < hashMapCharCount)
{
return false;
}

int iterator = 0;
for (iterator = parentIterator; iterator < parentIterator + hashMapCharCount; iterator++)
{
char targetChar = parentString[iterator];
int count = -1;
if (hashMap.TryGetValue(targetChar, out count))
{
if (count <= 0)
{
isSpecialSubstringFound = false;
break;
}

hashMap[targetChar] = count - 1;
}
else
{
isSpecialSubstringFound = false;
break;
}
}

if (isSpecialSubstringFound)
{
specialSubstring = parentString.Substring(parentIterator, hashMapCharCount);
}

return isSpecialSubstringFound;
}
}

public static class Log
{
public static void Comment(string message)
{
Console.WriteLine(" - " + message);
}
}

- Vivs May 31, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 vote

garimaa.blogspot.in/2012/04/program-in-c.html

- Answer : April 02, 2012 | 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