Amazon Interview Question for Software Developers


Country: United States
Interview Type: Phone Interview




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

import java.util.*;
public class Qus {
public static void main(String[] args) {
TreeSet set=new TreeSet();
set.add(new Csv("Alice",30));
set.add(new Csv("Bob",17));
set.add(new Csv("Clyde",49));
Iterator it= set.iterator();
while(it.hasNext())
{
Object ob=it.next();

System.out.println(ob);
}
}
}
class Csv implements Comparable
{
String name;
int age;

public Csv(String name,int age)
{
this.name=name;
this.age=age;
}
@Override
public int compareTo(Object o) {
if(o instanceof Csv)
{
Csv v=(Csv)o;
return this.age-v.age;
}
return 0;
}
public String toString()
{
return name+"\t"+age;
}
}

- Anonymous July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

import java.util.*;
public class Qus {
public static void main(String[] args) {
TreeSet set=new TreeSet();
set.add(new Csv("Alice",30));
set.add(new Csv("Bob",17));
set.add(new Csv("Clyde",49));
Iterator it= set.iterator();
while(it.hasNext())
{
Object ob=it.next();

System.out.println(ob);
}
}
}
class Csv implements Comparable
{
String name;
int age;

public Csv(String name,int age)
{
this.name=name;
this.age=age;
}
@Override
public int compareTo(Object o) {
if(o instanceof Csv)
{
Csv v=(Csv)o;
return this.age-v.age;
}
return 0;
}
public String toString()
{
return name+"\t"+age;
}
}

- Anonymous July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
1
of 1 vote

public static string SortByAge(string fileContent)
{
	var minHeap = new SortedDictionary<int, List<string>>();
	foreach(string line in fileContent.Split('\n'))
	{
		string[] parsed = line.Split(',');
		string name = parsed[0];
		int age = Convert.ToInt32(parsed[1]);

		if(!minHeap.ContainsKey(age))
		{
			minHeap.Add(age, new List<string>() { name });
		}
		else
		{
			minHeap[age].Add(name);
		}
	}

	StringBuilder sb = new StringBuilder();
	foreach(var kvp in minHeap)
	{	
		foreach(string name in kvp.Value)
		{
			sb.Append(string.Format("{0},{1}\n", name, kvp.Key));
		}
	}
	
	return sb.ToString();
}

- Nelson Perez July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
-2
of 2 votes

time complexity o(n2)

- pantjeevan98 July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

this is using heap , although a nested loop is used , the time complexity is (nlogn),
and the nested loop is just iterate all items from CSV files , the time complexity
should be O(n) and find min is O( logn)

- Scott July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

@pantjeevan98: @Scott is correct this is O(nlogn) as every insertion is O(logn) so n insertions is O(nlogn) then the double loop actually is O(n)

So this is O(nlogn + n) => O(nlogn)

- Nelson Perez July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think its simple case of merge sort, you have to sort the ages.

- learning_algo June 30, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

How abt putting ages inside an array and age(key) and name(value) inside a hash map.
Sort the age array. Then start traversing the sorted array and search inside the hash map for every array element stored as a key.

- rafa26 July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;
public class Qus {
public static void main(String[] args) {
TreeSet set=new TreeSet();
set.add(new Csv("Alice",30));
set.add(new Csv("Bob",17));
set.add(new Csv("Clyde",49));
Iterator it= set.iterator();
while(it.hasNext())
{
Object ob=it.next();

System.out.println(ob);
}
}
}
class Csv implements Comparable
{
String name;
int age;

public Csv(String name,int age)
{
this.name=name;
this.age=age;
}
@Override
public int compareTo(Object o) {
if(o instanceof Csv)
{
Csv v=(Csv)o;
return this.age-v.age;
}
return 0;
}
public String toString()
{
return name+"\t"+age;
}
}

- pantjeevan98 July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Radix Sort...as age will be max 100.. but ofcourse a treeset needs to be maintained!
just another apporach.

- liju.leelives July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.*;

public class CSV implements Comparable<CSV>{

private String name;
private int age;

public CSV(String name,int age){
this.name = name;
this.age = age;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}


@Override
public int compareTo(CSV o) {
if(this.age > o.getAge()){
return 1;
}else if(this.age < o.getAge()){
return -1;
}
return 0;
}

@Override
public String toString() {
return this.name + " "+this.age;
}

public static void main(String[] args) {
CSV ob1 = new CSV("Alice",30);
CSV ob2 = new CSV("Bob",17);
CSV ob3 = new CSV("Clyde",49);

List<CSV> list = new ArrayList<CSV>();

list.add(ob1);
list.add(ob2);
list.add(ob3);


Collections.sort(list);

System.out.print(list);

}
}

- Infinite Possibilities July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package com.cnu.ds.programs;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import com.cnu.ds.sorting.MergeSortVersion2;

public class PersonSortClient {
	public static void main(String[] args) {
		MergeSortVersion2 mergeSort = new MergeSortVersion2();
		Comparable<Person>[] persons = persons();
		System.out.println("Before sort");
		for (Comparable<Person> person : persons) {
			System.out.println(person);
		}
		mergeSort.sort(persons);
		System.out.println("After sort");
		for (Comparable<Person> person : persons) {
			System.out.println(person);
		}
	}

	public static Comparable<Person>[] persons() {
		List<Comparable<Person>> persons = new LinkedList<>();
		BufferedReader bufferedReader =null;
		try {
			 bufferedReader = new BufferedReader(new FileReader(
					"persons"));
			String personDetails = null;
			while ((personDetails = bufferedReader.readLine()) != null) {
				String details[] = personDetails.split(",");
				Person person = new Person(details[0],
						Integer.valueOf(details[1]));
				persons.add(person);
			}
			Person[] personss = new Person[persons.size()];
			return persons.toArray(personss);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if (bufferedReader!=null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}

- cnu1438 July 01, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

package com.cnu.ds.sorting;

/**
 * @author cnu8
 * @see It is the improved version of {@link MergeSort}
 */
public class MergeSortVersion2 extends Sort {

	private static Comparable<?>[] aux;

	@Override
	public void sort(Comparable<?>[] a) {
		aux = new Comparable[a.length];
		sort(a, 0, a.length - 1);
	}

	protected void sort(Comparable<?>[] a, int low, int high) {
		if (low < high) {
			int mid = low + (high - low) / 2;
			sort(a, low, mid);
			sort(a, mid + 1, high);
			merge(a, low, mid, high);
		}
	}

	private void merge(Comparable<?>[] a, int low, int mid, int high) {
		// !less(a[mid], a[mid + 1]) : No merge required if the last element of
		// first array is
		// less than or equal to the first element of second array. Because the
		// complete array is already in sorted order
		// !a[mid].equals(a[mid + 1]) -- check for equality of the above two
		// elements
		if (!less(a[mid], a[mid + 1]) || !a[mid].equals(a[mid + 1])) {
			for (int i = low; i <= high; i++) {
				aux[i] = a[i];
			}
			int i = low, j = mid + 1, k = low;
			while (i <= mid && j <= high) {
				if (less(aux[i], aux[j])) {
					a[k] = aux[i];
					i++;
				} else {
					a[k] = aux[j];
					j++;
				}
				k++;
			}
			while (i <= mid) {
				a[k] = aux[i];
				i++;
				k++;
			}
			while (j <= high) {
				a[k] = aux[j];
				j++;
				k++;
			}
		}
		// Testing the output of array : a after merging
		// for (int k2 = low; k2 <= high; k2++) {
		// System.out.print(a[k2]);
		// }
		// System.out.println();
	}

	public static void main(String[] args) {
		char[] aa = "MERGEEXAMPLE".toCharArray();
		System.out.println("Before Sort");
		Comparable<?>[] a = new Comparable[aa.length];
		for (int i = 0; i < a.length; i++) {
			a[i] = aa[i];
		}
		for (Comparable<?> comparable : a) {
			System.out.print(comparable);
		}
		System.out.println();
		MergeSortVersion2 mergeSortVersion2 = new MergeSortVersion2();
		mergeSortVersion2.sort(a);
		if (mergeSortVersion2.isSorted(a)) {
			System.out.println("After Sort:");
			for (Comparable<?> comparable : a) {
				System.out.print(comparable);
			}
		} else {
			System.out.println("Array is not sorted");
		}
	}
}

- cnu1438 July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

package com.cnu.ds.sorting;

@SuppressWarnings("rawtypes")
abstract public class Sort {
	int count;

	protected boolean isSorted(Comparable[] a) {
		for (int i = 0; i < a.length - 1; i++) {
			// a[i].equals(a[i + 1]) is to allow duplicate elements
			if (less(a[i], a[i + 1]) || a[i].equals(a[i + 1])) {
				continue;
			}
			return false;
		}
		return true;
	}

	@SuppressWarnings("unchecked")
	protected boolean less(Comparable i, Comparable j) {
		return i.compareTo(j) < 0;
	}

	protected void excahnge(Comparable[] a, int i, int j) {
		Comparable temp = a[i];
		a[i] = a[j];
		a[j] = temp;
	}

	public abstract void sort(Comparable<?>[] a);
}

- cnu1438 July 01, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here is C++ solution using set

class Person {
	char name[80];
	int age;
	public:
	Person(char *_name,int _age) : age(_age) {
		strcpy (name, _name);
	}
	Person(const Person& p1) : age(p1.age) {
		strcpy (name, p1.name);
	}
        /* operator less than required to sort SET elements*/
	bool operator < (const Person& p1) const
	{
		return (age < p1.age);
	}
       /* Display the elements */
        friend	ostream& operator << (ostream& ostr, const Person& p1) 
	{
		return (ostr << p1.name << " "<< p1.age << endl);
	}
};

int main () {
	ifstream if1 ("input.csv");
	string strLine;
	set<Person> personSet;

	while ( if1.good())
	{
		int age;
		char name[80],ageStr[4];
	        if (getline (if1, strLine) ) {
                    /* read name and age in character string*/
	            sscanf (strLine.c_str (),"%[^,],%s", name, ageStr);
                   /*converting age from char string to numeric */
		    age= atoi (ageStr);
		    personSet.insert (Person(name, age));
		}
	}

       /* iterate over the set */
	for (set<Person>::iterator itr=personSet.begin (); itr!= personSet.end (); itr++)
		cout << *itr;
}

- Sach July 02, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

The perl way:

my $hash={};
my $arr = [];
while(<STDIN>) {
	chomp;
	my ($name, $age) = split ',' ;
        $hash->{$name} = $age;
}
print sort {$hash->{$a} cmp $hash->{$b} }  keys %$hash

Using Priority queue in C++:

#include<string>
#include<iostream>
#include<queue>
#include<cstdlib>

struct Person {

    std::string name;
    int age;
    Person(std::string n , int a):name(n), age(a) {}
};

struct personCompare {

    bool operator ()(const Person &p1, const Person &p2) const {
        return p1.age > p2.age;
    }   
};

int main() {
    std::priority_queue<Person, std::vector<Person>, personCompare> pq; 
    std::string line;
    while (std::getline(std::cin, line)) {
        std::string name = line.substr(0, line.find_first_of(',',0));
        int age = std::atoi(line.substr(line.find_first_of(',',0) + 1).c_str());
        Person p(name,age);
        pq.push(p);
    }   
    while (!pq.empty()) {
            Person p = pq.top();
            std::cout << p.name << std::endl;
            pq.pop();
    }   
}

- lalit.kumar.bhasin July 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

I think Bucket sort(assuming data is really huge) should be a good choice.In linear time and linear space. Because the age cannot be more than biggest of all(find in linear time).

- minhaz July 06, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

This is a trick question.
Any one of the options work but each of them needs to be maintained (reordering a tree, sorting etc.) and not use something very crucial: it's an age field. use the fact that there's a maximum of lets say 100 (150 if you REALLY want to be optimistic :) ).
Use an array of linkedList, and just add each new value to the right place.
You can use a TreeSet instead of linkedlist and that way also each age is sorted by the name.

- Ben July 16, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class SortObject {
	public static void main(String[] args){
		SortObject sort = new SortObject();
		sort.SortObj();
	}
	public void SortObj(){
		List<CSV> list = new ArrayList<>();
		list.add(new CSV("Alice", 30));
		list.add(new CSV("Bob", 17));
		list.add(new CSV("Clyde", 49));
		Collections.sort(list);
		for(CSV csv: list){
			System.out.println(csv.getName() + " = "+csv.getAge());
		
		}
		
	}
	
}

class CSV implements Comparable<CSV>{
	private String name;
	private int age;
	
	public CSV(String name, int age){
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	@Override
	public int compareTo(CSV o) {
		if(age > o.getAge())
			return 1;
		else if(age == o.getAge())
			return 0;
		else
			return -1;
	}



}

- richagupta00007 September 14, 2015 | 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