JSDUDE
BAN USER
- 2of 2 votes
AnswersWrite a function that takes an array of positive and negative integers and a number. This function should return true if the array contains a contiguous sub array that sums up to the number (2nd input).
- JSDUDE in United States
He wanted an O(n) algorithm.| Report Duplicate | Flag | PURGE
Snap Inc Software Developer Arrays - 3of 3 votes
AnswersGiven the following set of strings, write a function that stores this information.
- JSDUDE in United States
// /Electronics/Computers/Graphics Cards
// /Electronics/Computers/Graphics Cards
// /Electronics/Computers/SSDs
// /Electronics/Computers/Graphics Cards
// /Electronics/Computers/SSDs
// /Electronics/TVs
// /Electronics/Computers/Graphics Cards
// /Electronics/TVs
// /Electronics/TVs
// /Garden
// /Automotive/Parts
Your datastructure should be able to provide information as such:
// / = 11
// /Electronics = 9
// /Electronics/Computers = 6
// /Electronics/Computers/Graphics Cards = 4
// /Electronics/TVs = 3
// etc
// ["/Electronics/Computers/Graphics Cards", "/Garden"]| Report Duplicate | Flag | PURGE
NVIDIA Senior Software Development Engineer Data Structures Trees and Graphs - 1of 1 vote
Answers1. Difference between arrays and link list
- JSDUDE in United States for Alexa
1.1 How to prepend each of the above with extra data
2. Hash-table. What datastructure to use to create one. How to resolve collision| Report Duplicate | Flag | PURGE
Amazon Software Developer Data Structures - 0of 0 votes
Answers/*
- JSDUDE in United States for Alexa
Amazon employees are encouraged to learn and be curious, and this means employees can transfer teams within the company easily.
This usually means they'll move to a new building, and for those who have parking, they'd need to swap parking spots.
The task is that given a list of employees who want to swap parking spots, write a function that can match them up 1 to 1.
The output can simply be tuples of aliases.
Each alias should only be matched once.
Input-
alias fromBuilding toBuilding
adrian building1 building2
john building2 building1
andrew building3 building2
william building4 building3
John building2 building4
Doe
output-
adrian,john
*/| Report Duplicate | Flag | PURGE
Amazon Software Developer Algorithm - 0of 0 votes
AnswersElevator system for a tall building
- JSDUDE in United States| Report Duplicate | Flag | PURGE
Tableau Software Engineer / Developer design - -1of 1 vote
AnswerGiven a collection of buildings determine the length of a skyline.
- JSDUDE in United States
Length of the skyline will be the line you draw over the top of the buildings in the skyline.
Remember you have to ignore the shorter buildings that get shadowed by taller buildings in front of them| Report Duplicate | Flag | PURGE
Tableau Software Engineer / Developer Algorithm - 0of 0 votes
AnswersWrite an itoa
- JSDUDE in United States| Report Duplicate | Flag | PURGE
Booking.com Software Developer Algorithm String Manipulation - 0of 2 votes
AnswersSerialize & Deserialize a binary tree
- JSDUDE in United States| Report Duplicate | Flag | PURGE
Uber Software Developer Trees and Graphs - 0of 0 votes
AnswersImplemented a bounded queue:
- JSDUDE in United States for Customer experience
Read:
If queue is empty, wait till it can return a value with time out
If another thread is reading from the queue then wait till that thread is done
Remove the first element from the queue and return it
Do not block if a thread is writing into the queue
Write:
If queue is full, wait till one value is read with time out
If another thread is writing to the queue, wait till that thread is done
Write the element at the end of the queue
Do not block if a thread is reading from the queue| Report Duplicate | Flag | PURGE
Walmart Labs Software Developer Data Structures Threads - 1of 1 vote
AnswersGiven a start string, end string and a set of strings, find if there exists a path between the start string and end string via the set of strings.
- JSDUDE in United States for Customer experience
A path exists if we can get from start string to end string by changing (no addition/removal) only one character at a time. The restriction is that the new string generated after changing one character has to be in the set.
start: "cog"
end: "bad"
set: ["bag", "cag", "cat", "fag", "con", "rat", "sat", "fog"]
one of the paths: "cog" -> "fog" -> "fag" -> "bag" -> "bad"| Report Duplicate | Flag | PURGE
Walmart Labs Software Developer Algorithm String Manipulation - 0of 0 votes
AnswersGiven an array of integers (+ve & -ve) find two equal sized contiguous non-overlapping sub-arrays with maximum dot-product
- JSDUDE in United States for Customer experience| Report Duplicate | Flag | PURGE
Walmart Labs Software Developer Algorithm Arrays - 0of 0 votes
AnswersWrite an OO class system for individual-contributors, managers, directors.
- JSDUDE in United States for Customer experience| Report Duplicate | Flag | PURGE
Walmart Labs Software Developer Object Oriented Design - 0of 0 votes
AnswersMinimize the cost to chop the log into pieces of desired lengths. The cost to cut any piece is the max of the two lengths generated out of cutting the wood. e.g. If a 14 unit log is cut into 2 pieces of lengths 6 and 8, cost is 8.
- JSDUDE in United States for Customer experience
Write a function that takes the total length of the log and an array of piece lengths and returns the cheapest sequence to do this along with the cost| Report Duplicate | Flag | PURGE
Walmart Labs Software Developer Algorithm - 0of 0 votes
AnswersGiven an existing inventory Oracle Database system and UI. The UI should update itself as soon as the db gets updated
- JSDUDE in United States for Customer experience
There is a tool that people use to dump inventory data (one row at a time or bulk insert via data in files)
Currently a new system is built with new UI using No Sql database.
Write a bridge that will update the new UI and populate the No SQL database, so that the new UI has real time updates as the tool has updated.| Report Duplicate | Flag | PURGE
Walmart Labs Software Developer System Design - -1of 1 vote
Answers
- JSDUDE in United Statespublic class StringUtilities { /** * Count the maximum depth of parenthesis nesting, i.e. "abc(123(xyz))m(((n)))o" -> 3. * * @param input * any string * @return deepest parenthesization level * @throws IllegalArgumentException * if input is null or contains a mismatch "a)b(c" or "a(b" */ public static int nestedParenthesisDepth(String input) throws IllegalArgumentException { //... } }
| Report Duplicate | Flag | PURGE
Walmart Labs Software Engineer Algorithm String Manipulation - 4of 4 votes
AnswersGiven a big rectangular plot of land that has rectangular or square sized buildings (all sides of every building are parallel to the big rectangular plot)... find the location and dimensions of the largest square that can be built in this rectangular plot
- JSDUDE in United States| Report Duplicate | Flag | PURGE
Microsoft SDE-2 Algorithm - 1of 1 vote
AnswersYou are tasked with implementing a method that returns the lowest possible number that could be generated after removing n characters from a string of digits. The method signature should look like:
public static string GenerateLowestNumber(string number, int n)
Where the number parameter is a string that contains a number (e.g. “4205123”), and the n parameter represents the number of characters to remove from the string. The goal of this method is to return the lowest number that can be generated by removing n characters from the number provided while keeping the positions of the remaining characters relative to each other the same (i.e. the method should remove n characters from the string, but it cannot re-order the characters).
- JSDUDE in United States for Cloud + Enterprise
For example, if number is “4205123” and n is 4, the lowest possible number that can be generated after removing any 4 characters is “012”. If number is “216504” and n is 3, the lowest possible number that can be generated after removing 3 characters is “104”.| Report Duplicate | Flag | PURGE
Microsoft Software Developer Algorithm String Manipulation - 0of 0 votes
AnswersIdentify the flaws / limitations in the following ConvertToNumber method:
- JSDUDE in United States for Cloud + Enterprisepublic static bool ConvertToNumber(string str) { bool canConvert = false; try { int n = Int16.Parse(str); if (n != 0) { canConvert = true; } } catch (Exception ex) { } bool retval = false; if (canConvert == true) { retval = true; } return retval; }
| Report Duplicate | Flag | PURGE
Microsoft Software Developer Debugging - 0of 0 votes
AnswersYou are tasked with migrating data between two systems that store movie metadata. The first system, which you are to use as input, keeps their movie metadata in the following structure:
MovieName ContributorType ContributorName
Pulp Fiction Director Quentin Tarantino
Pulp Fiction Actor John Travolta
Pulp Fiction Actor Samuel L. Jackson
Titanic Director James Cameron
The second system, which you are to output to, uses the following object for movie information:class MovieInformation { public string Name { get; set; } public string Director { get; set; } public List<string> Actors { get; set; } }
The first system provides an IDataReader that lets you access their data. Their data is always sorted on MovieName. You can call Read on the IDataReader to move the cursor to the next entry, and you can call GetString on the IDataReader to get the movie name, contributor type, and contributor name. For example, with the above data, if you were to call:
MovieDataReader dataReader = new MovieDataReader(); int movieNameOrdinal = dataReader.GetOrdinal( "MovieName" ); int contributorTypeOrdinal = dataReader.GetOrdinal( "ContributorType" ); int contributorNameOrdinal = dataReader.GetOrdinal( "ContributorName" ); while ( dataReader.Read() ) { string movieName = dataReader.GetString( movieNameOrdinal ); string contributorType = dataReader.GetString( contributorTypeOrdinal ); string contributorName = dataReader.GetString( contributorNameOrdinal ); }
Then at the end of the first iteration of this while loop, movieName would be “Pulp Fiction”, contributorType would be “Director” and contributorName would be “Quentin Tarantino”.
The second system provides a single method for posting movie information to their DB. This method should only ever be called once per movie:class MovieInformationDatabase { public void SaveMovieInformation( MovieInformation information ) { } }
Implement a method that migrates all of the data from the first system to the second system
- JSDUDE in United States for Cloud + Enterprise| Report Duplicate | Flag | PURGE
Microsoft Software Developer Algorithm - 2of 2 votes
AnswersGiven a 4 X 4 game slot that has random alphabets in all the slots
- JSDUDE in United States
Write a function that takes the keyboard and the word as input and returns true if the word can be formed
False otherwise.
A word can be formed on the board by connecting alphabets adjacent to each other (horizontal, vertical and diagonally)
Same alphabet should not be reused.| Report Duplicate | Flag | PURGE
Facebook Software Engineer / Developer Algorithm - 1of 1 vote
AnswersGiven a set of n people, find the celebrity.
- JSDUDE in United States
Celebrity is a person who:
1. Knows only himself and no one else
2. Every one else knows this person
You are given the following helper function:
bool knows(i, j);
Returns:
True: If i knows j
False: otherwise
I proposed the O(n2) algorithm at first but he wanted me to improve on it. He wanted an O(n) algorithm| Report Duplicate | Flag | PURGE
Facebook Software Engineer / Developer - 0of 0 votes
AnswersYou have a list of words with ranking.
- JSDUDE in United States
Now you need to create a function that will take this list as input and provide a way so that a T9 keyboard can provide three top results of probable words based on rankings for the numbers punched in.| Report Duplicate | Flag | PURGE
Facebook Software Engineer / Developer Algorithm - 0of 0 votes
Answers//Given a method that takes in a positive non-zero number N, return from that method the total number of factors of N. //Start with O(n) solution and make it faster if we have time
- JSDUDE in United States| Report Duplicate | Flag | PURGE
F5 Networks Software Engineer / Developer Algorithm Math & Computation - 0of 0 votes
AnswersImplement the divide of two integers without using the divide operator.
- JSDUDE in United States for AWS Infrastructure Planning, Analysis and Optimization
After implementing the O(n) algorithm to subtract the divisor from the divider, he asked me to implement a better algorithm.
I started working towards bit manipulation, but ran out of time.
He also hinted that I could have used binary search. Not sure how though.| Report Duplicate | Flag | PURGE
Amazon SDE-2 Math & Computation - 0of 0 votes
AnswerGiven a stack of magazines create an anonymous love note (pick words or alphabets from the magazine and create the note)...
- JSDUDE in United States for AWS Infrastructure Planning, Analysis and Optimization
He gave me the choice of handling words or alphabets
Assume you have a scanned copy of the magazine as a string.
Once I implemented both words and alphabets, he asked me to scale it to mass production and maximize the throughput of a fulfillment center handling this| Report Duplicate | Flag | PURGE
Amazon SDE-2 Algorithm - 2of 2 votes
AnswersDesign a robot that will take your order and make sandwiches for you.
- JSDUDE in United States for AWS Infrastructure Planning, Analysis and Optimization
Once I was done with this, I was supposed to extend it to have multiple robots doing this job like an assembly line handling multiple sandwiches and other edible items
Once I handled that, he asked me to create a web service for this that will handle online ordering. He also wanted me to implement fulfillment centers| Report Duplicate | Flag | PURGE
Amazon SDE-2 Object Oriented Design - 2of 2 votes
AnswersGiven a large array of unsigned ints, quickly find two who's sum is 10
- JSDUDE in United States for Software Developer, Infrastructure Planning, Analysis and Optimization
Then the interviewer asked me to write test cases.
Followed by how to implement this on a distributed system, where multiple systems can read/write simultaneously on a shared cache (HINT: It is ok if you do not return the first instance)| Report Duplicate | Flag | PURGE
Amazon SDE1 Algorithm Arrays - 0of 0 votes
AnswersGiven ~300k words with an average length of 7 in a file.
- JSDUDE in United States
All words are dictionary correct words.
Print all the anagrams that are present in this list of words without repeating them.
E.g. if the list has:
ACT
BAT
CAT
TAB
TAC
print:
ACT, CAT, TAC
BAT, TAB| Report Duplicate | Flag | PURGE
Amazon Software Engineer / Developer Algorithm Data Structures - -1of 1 vote
AnswersDesign the algorithm and the system for a WebCrawler.
- JSDUDE in United States
The webcralwler will be provided millions of URLs. The webpage will be downloaded and then parsed for more URLs. If more URLs are found then they should also be downloaded and parsed.
He was interested in:
1. Scale to handle millions of URLs
2. What are the bottle necks in the system? How will you resolve them| Report Duplicate | Flag | PURGE
Amazon Software Engineer / Developer Object Oriented Design - 2of 2 votes
AnswersDesign a vending machine
- JSDUDE in United States| Report Duplicate | Flag | PURGE
Amazon Software Engineer / Developer Object Oriented Design - 0of 0 votes
AnswersGiven a sorted array with some sequenced numbers and some non-sequenced numbers. Write an algorithm that takes this array as an input and returns a list of {start, end} of all consecutive numbers. Consecutive numbers have difference of 1 only.
E.g. of array:
[4, 5, 6, 7, 8, 9, 12, 15, 16, 17, 18, 20, 22, 23, 24, 27]
- JSDUDE in United Statespublic class Range { private int begin; private int end; public int begin { get; set; } public int end { get; set; } }
| Report Duplicate | Flag | PURGE
Amazon Software Engineer / Developer Arrays - 0of 0 votes
AnswersThis test was on https://www.hackerrank.com
- JSDUDE in United States for TRMS
Input is a string of Bytes E.g.341B
Convert it to human readable form: 3 characters long (excluding decimal)
No trailing or leading zeros
E.g:
Input 341B
Output 341B
Input 12345B
Output 12.3K
Input 1234567B
Output 1.23M
Input 1000000000B
Output 1G
Do not round off
Assume input will not be more than 1G
For this problem 1000B = 1K, so on and so forth| Report Duplicate | Flag | PURGE
Amazon Software Engineer / Developer Algorithm - 0of 0 votes
AnswersDifference between struct and class.
- JSDUDE in United States for LSB
When would you use one over the other
What is padding? Do both struct and class have padding| Report Duplicate | Flag | PURGE
Expedia SDE-2 Object Oriented Design - 0of 0 votes
AnswersExplain the underlying working of how inherited function gets invoked. So if Dog and Cat, inherited from Animal, inherit Eats. How does the right Eats get called for Dog/Cat
- JSDUDE in United States for LSB
private inheritance vs composition
When would you use private inheritance| Report Duplicate | Flag | PURGE
Expedia SDE-2 Object Oriented Design - 0of 0 votes
AnswersWhat is a static function? Explain in detail
- JSDUDE in United States for LSB| Report Duplicate | Flag | PURGE
Expedia SDE-2 Object Oriented Design - 0of 0 votes
AnswersImplement an atoi function in C++
- JSDUDE in United States for LSB| Report Duplicate | Flag | PURGE
Expedia SDE-2 Algorithm - 0of 0 votes
AnswersDifference between threads and process.
- JSDUDE in United States for LSB
When would you use one vs the other
Where on the stack are values stored for their local variables?
If there are two threads each with two local variables, where will these variables be stored| Report Duplicate | Flag | PURGE
Expedia SDE-2 Threads - 1of 1 vote
AnswersDifference between concurrency and parallelism
- JSDUDE in United States
How has threading helped concurrency and parallelism?| Report Duplicate | Flag | PURGE
Ebay SDE1 Threads - 1of 1 vote
AnswerFormula for nth PI is (-1^n)/(2n+1). Write an efficient way to calculate this.
- JSDUDE in United States
After i wrote a recursive and iterative solution, she wanted a faster solution. So i went to threading.
Eventually she said that if the value of n is a million and you can't have million threads how will you distribute:
Problem is as n increases the above computation becomes time consuming and hence cannot be simply split in ranges.
She hinted me towards: Queue of jobs, threads picking jobs and en-queuing the work| Report Duplicate | Flag | PURGE
Ebay SDE1 Math & Computation Threads - 0of 0 votes
AnswersYou are given a 2D array that is your sea. It has more than one ships which don't overlap each other. All ships are not necessarily of the same size.
- JSDUDE in United States
You are to improve on performance and space is no concern.
Write a program that takes in two co-ordinates:
If the attack co-ordinates did not have a ship, print "Missed"
If the attack co-ordinates have a ship, print "Attacked Ship <Name>"
If the attack co-ordinates have a the same part of the attacked ship, print "Already Attacked"
If the last piece of the un-attacked ship was attacked print: "Ship sunk".| Report Duplicate | Flag | PURGE
Ebay SDE1 Coding Data Structures - 0of 0 votes
AnswersGiven a binary tree with each node having a pointer to its parent, Write a function that can find the immediate right neighbor of a given node. Don't use BFS.
- JSDUDE in United States
Node* RightNeighbor(Node* node)
Note: Root of the tree is not given| Report Duplicate | Flag | PURGE
Ebay SDE1 Trees and Graphs - 0of 0 votes
AnswersThere is a file on a server. There are 3 access levels to this file: 1. Read\Write 2 Read 3. No access.
- JSDUDE in United States
A person can: 1. Copy a file. 2. Edit it on the server 3. Overwrite the existing file on the server
Write all the test cases for this scenario| Report Duplicate | Flag | PURGE
Ebay SDE1 test - 0of 0 votes
AnswersN nodes, each node consists of a couple fields and methods. These are:
- JSDUDE in United States
int id; //every node has an ID. All of these IDs are sequential, and begin with 0. I.e. all ids are uniquely in the range of 0 t N-1
int val; //every node has a value
int max; //max = N. Every node knows how many nodes are in the system.
void send(int idTo, int payload)
int recv(int idFrom)
Write a single piece of code which runs on every node simultaneously, such that when it is finished running every node in the system knows the sum of the values of all the nodes in the system.| Report Duplicate | Flag | PURGE
Ebay Software Engineer / Developer Trees and Graphs - 0of 0 votes
AnswerGiven:
- JSDUDE in United States
Array of n objects of type Object
///<summary>
/// Given two objects, this function returns a value between 0-100 depending on the relation of the two objects
/// <param1: objToBeCompared>Any object instance which has to be compared to the objReference</param1: objToBeCompared>
/// <param2: objReference>Instance of an object against which the other instance of the Object is to be compared</param2: objReference>
/// <return>A value between 0-100</return>
///</summary>
int Compare(Object objToBeCompared, Object objReference)
Now implement a function:
///<summary>
/// Given an object array of length n, a reference object this function returns the top numberOfMatches matches based on Compare(obj, obj) function's return value
/// Start with the object(s) that return 99 and go up till you find numberOfMatches element
/// The return array doesn't have to be sorted by the Compare value
/// <param1: objects>Array of n Object from which numberOfMatches have to be selected</param1: objects >
/// <param2: ObjectToBeCompared>Object against which the other objects need to be compared to</param2: ObjectToBeCompared>
/// <param3: numberOfMatches>number of matches to be returned</param3: numberOfMatches>
/// <return>Array of numberOfMatches objects</return>
///</summary>
Object[] FindTopMatch(Object[] objects, Object ObjectToBeCompared, int numberOfMatches)| Report Duplicate | Flag | PURGE
Data Structures - 0of 0 votes
AnswersQ1. What is inheritance
- JSDUDE in United States
2. Polymorphism
3. Diff between Pure Virtual class and Virtual Class
4. Adv and dis-adv of C# and C++ over each other
5. Sequence in which constructors are called when a child class object is created and why is the order so.| Report Duplicate | Flag | PURGE
Microsoft SDE1 Object Oriented Design - 1of 1 vote
AnswersGiven a rotated sorted array, find the MIN of the array.
- JSDUDE in United States
He pointed out a mistake in my
int middle = (begin+end)/2 which could overflow if the array size was INT_MAX.
Answer was:
middle = (end-begin)/2 + begin| Report Duplicate | Flag | PURGE
Microsoft SDE1 Arrays - 2of 2 votes
AnswersGiven a binary tree, print its perimeter:
- JSDUDE in United States
node, left->most nodes from top to bottom, leaf nodes from left-> right, right->most nodes from bottom to top
----------------------------1
-----------------------2--------3
------------------4-----5-----6--------7
-------------8------9-----10------11-----12
should print:
1-2-4-8-9-5-10-11-12-7-3
5 because it doesn't have any children. 10 and 11 are children of 6 and 8 & 9 are children of 4.
Apologies for the messy diagram.| Report Duplicate | Flag | PURGE
Microsoft SDE1 Trees and Graphs - 0of 0 votes
AnswersGiven a Binary tree and a node, return it's post-order predecessor
- JSDUDE in United States| Report Duplicate | Flag | PURGE
Microsoft SDE1 Trees and Graphs - 0of 0 votes
AnswersSingle Initialization :
- JSDUDE in United States
Global variable x, initialized to 0.
Implement a function that can be called by multiple threads simultaneously or sequentially.
The value of x should be set to the current time only once. If it is already set, the value shouldn't be updated.
Make sure that the function doesn't become a bottleneck| Report Duplicate | Flag | PURGE
Microsoft SDE1 Threads - 0of 0 votes
AnswersGiven a BT and 2 nodes, find LowestCommonAncestor
- JSDUDE in United States| Report Duplicate | Flag | PURGE
Microsoft SDE1 Trees and Graphs - 2of 2 votes
AnswersFind the Max sum subsequence in array
- JSDUDE in United States| Report Duplicate | Flag | PURGE
Microsoft SDE1 Arrays - 0of 0 votes
AnswerThere is a HealthMonitor and two Servers (Primary and Secondary), all connected to one and another.
- JSDUDE in United States
The HealthMonitor keeps pinging both the servers at specific time intervals and waits for their response for a time-out period after the request has been sent.
The server responds with a health status of itself and of its neighbor (meaning Primary responsds: OK; NEIGHBOR_OK)
Implement the server's code to send and receive responses and then take action based on response.| Report Duplicate | Flag | PURGE
Amazon SDE1 Threads - 3of 3 votes
AnswersWrite a class that will have following functions:
- JSDUDE in United States
long CheckOut()
CheckIn(long)
Range of values is 1 to LONG_MAX
At any given point in time checkout should return the minimum available LONG number
Checkin can return the value back
No need to check for border conditions (e.g. check out when all values are exhausted)
Implement:
1. long checkout()
2. void checkIn(long input)| Report Duplicate | Flag | PURGE
Amazon SDE1 Data Structures - 0of 0 votes
AnswersWrite a class For Contacts on a device
- JSDUDE in United States
Implementing Search a contact was the biggest problem I faced (because search should potentially search: FirstName, LastName, Address, PH#, Email etc)| Report Duplicate | Flag | PURGE
Amazon SDE1 Object Oriented Design - 0of 0 votes
AnswersImplement:
1. a search that will return all the strings that match a sub-string
2. an insert into this datastructure
- JSDUDE in United StatesClass { Insert (string str){}; List<strings> Predictions(string subString){}; }
| Report Duplicate | Flag | PURGE
Amazon SDE1 Trees and Graphs - 0of 0 votes
AnswersA video streaming server is generating the following data. Find the potential customers facing buffering issues.
A person is said to face buffering issues when he hits the play button multiple times on the same video
You are given a huge file (say 1GB) that contains the following data:
CustomerId-TimeStamp-Event-VideoId-Videolength
0040 -01.00pm -Play -Video1 -02:30:00
Write code for this. What data structure will you use
He also said, lets say all the parsing is taken care of and you are given a collection of classes that contain the above data:
- JSDUDE in United StatesClass { CustomerId TimeStamp Event VideoId }
| Report Duplicate | Flag | PURGE
Amazon Software Engineer in Test Data Structures - 0of 0 votes
AnswerDesign a furniture store with Tables and chairs. Write a constructor for chair and table
- JSDUDE in United States| Report Duplicate | Flag | PURGE
Amazon Software Engineer in Test Object Oriented Design - 1of 1 vote
AnswersQ:
Given a binary tree with nodes that have left, right pointers pointing to the left and right children respoectively. It also has a neighbor pointer that currently Points to null.
Write a function to make it point to its neighbor.
E.g1 2 3 4 5 6 7
1.sibling should point to null
- JSDUDE in United States
2.sibling should point to 3
3.sibling should point to null
4.sibling should point to 5
5.sibling should point to 6
6.sibling should point to 7
7.sibling should point to null
Iteration and Recursion both| Report Duplicate | Flag | PURGE
Microsoft SDE1 Trees and Graphs - -2of 2 votes
Answers//Q. Given an array of integers,write a function that retrieves unique instances of any duplicates, returning them in a //new array -
- JSDUDE in United States
// [2,1,2,4,3,1,5,1]
//= [2,1]
// [1,1,1,1,1,1,1,1,1]
// =[1]
// Write test cases for this function| Report Duplicate | Flag | PURGE
Amazon Software Engineer in Test Arrays Testing - 0of 0 votes
Answers1. What is difference between override and overload
- JSDUDE in United States
2. abstract. when will u use abstract
3. what is an interface
4. what is difference betwwen array and link list
5. what is a tree
6. what is a map\dictionary
7. Explain (orally) how would you implement a dictionary via a tree| Report Duplicate | Flag | PURGE
Amazon Software Engineer / Developer C++ - 0of 0 votes
AnswersThere are different buildings in one environment, each with machines that can handle one request at a time. How would you design the request handling so that there is no single fail-point and is scalable.
- JSDUDE in United States
Hint: It is ok if a request is sent to a machine that is already servicing another request. We can handle requests that come back from a machine. But he didnot want a lock on a single file that contained the data of empty machines
Follow up question was, lets say BLDG-A has 250 free machines, BLDG-B has 500 free machines, BLDG-C has 100 free machines and BLDG-D has 0. How would you assign requests? What if you had 850 requests at the same time? Why would you assign what you did?| Report Duplicate | Flag | PURGE
Amazon Software Engineer / Developer Distributed Computing - 0of 0 votes
AnswersClass and Data Structure Design for a "metric" system to determine the top song of a band. Two Web Service calls:
- JSDUDE in United States
void play(String bandname, String songname);
String topSong(String bandname);
CONSTRAINTS: For this exercise we should constrain the design to a single server and do NOT use a database, but in memory data structure.
SAMPLE INPUT/OUTPUT
play("Guns N Roses", "Welcome To the Jungle");
topSong("Guns N Roses") => "Welcome To the Jungle"
play("Guns N Roses", "Sweet Child of Mine");
topSong("Guns N Roses") => "Welcome To the Jungle"
play("Guns N Roses", "Sweet Child of Mine");
topSong("Guns N Roses") => "Sweet Child of Mine"
scale the architecture| Report Duplicate | Flag | PURGE
Amazon Software Engineer / Developer Data Structures Object Oriented Design
3 Answers Looking for TRIE Qs
I hear that TRIE is becoming a popular interview Q but don't see any good questions\solutions posted here. Yes, I searched with the keyword TRIE and the results weren't very promising.
- JSDUDE June 06, 2013
Can you please point me to some good resources for TRIE (not wikipedia please...)
Thank you in anticipation.| Flag | PURGE
Assume the dictionary is stored as a TRIE and has the following functions:
bool isPotentialWord(String str)
e.g. "qs" will return false since no word starts with qs
"ca" will return true as "cat", "category", "cast" etc.... are words
bool isWord(String str)
will return true if given word is a string
List<String> allPotentialStrings(String inputStr)
{
if(String.IsEmpty(inputStr))
return null;
return allPotentialStrings(inputStr, 0);
}
List<String> allPotentialStrings(String inputStr, int startIndex)
{
if(startIndex > inputStr.length - 1)
return ".";
List<String> outputStr = new List<String>();
String currStr = "";
for(int index = startIndex; index < inputStr.length; ++index)
{
currStr += ch;
if(!isPotentialWord(currStr))
break;
else if(!isWord(currStr))
continue;
else
{
List<String> restStr = allPotentialStrings(inputStr, index + 1);
if(null == restStr)
continue;
foreach(String str in restStr)
outputStr.add(currStr + " " + str);
}
}
return outputStr;
}
void FindIntsWithSum(unsigned int[] array, unsigned int sum)
{
if(0 == array.length)
return;
Dictionary<unsigned int, unsigned int> myDict = new Dict();
for(int index = 0; index < array.length; ++index)
{
if(myDict.contains(sum - array[index]))
{
Console.WriteLine("{0} & (1}", array[index], myDict.key(sum - array[index]));
return;
}
else
{
myDict.add(array[index]);
}
}
Console.WriteLine("This array does not contain values that sum upto: {0}", sum);
return;
}
// Test cases
// Empty array
Single element array
Large array -- Blow the memory
Small array
Arrays with lot of duplicates
Array without sum of the integer ...
Array with multiple combination...
Performance, Memory: (Large and small array)
Simple tests: Small arrays with sum present : Basic P1
Check for buffer overflow
@LV: psuedo code
class Product
{
item#, prod#, category, title, author, etc...
}
void buildDS(File f, char delimiter)
{
if(null == f)
return;
List<Product> products = new List<Product>();
Dictionary<string, List<int>> index_title = new Dictionary<>(string, List<int>);
// Add one dictionary per queriable meta-data (title, category, author)
while(!f.eof)
{
string line = f.readLine();
// Handle bad line scenarios
// Create product instance and populate
string[] infos = string.tokenize(line, delimiter);
products.add(new Product(infos[0], ... infos[infos.length - 1]));
index_title.add(prod.title, products.length - 1);
// Update all the dictionaries created
}
}
HTH :)
- JSDUDE October 24, 2014void print(List<Node> listNodes)
{
if(listNodes.isEmpty)
return;
Dictionary(int, List<Node>) dict = new ;
int maxHeight = -1;
int maxWidth = -1;
// Update dictionary
foreach(node in listNodes)
{
int height = getHeight(node);
dict[index].List.AppendAtEnd(node);
int width = dict[height].List.length;
maxHeight = (height > maxHeight) ? height : maxHeight;
maxWidth = (width > maxWidth) ? width : maxWidth;
}
// Print
for(int width = 0; width < maxWidth; ++width)
{
for(int index = 0; index < maxHeight; ++index)
{
Node temp = null;
if(null != dict[index].List.getValueAt(width))
temp = dict[index].List.getValueAt(width);
string str = (null == temp) ? "\t" : temp.value.toString();
print(str);
}
println();
}
}
int getHeight(Node node)
{
int height = 0;
while(null != node.parent)
node = node.parent;
return height;
}
static int maxDivide(int num, int divider)
{
while(num % divider == 0)
num = num / divider;
return num;
}
static bool isNumberUgly(int num)
{
if (0 == num)
return false;
return maxDivide(maxDivide(maxDivide(num, 2), 3), 5) == 1;
}
static int findNthUglyNumber(int n)
{
int num = 1;
int count = 1;
while (count < n)
{
++num;
if (isNumberUgly(num))
++count;
}
return num;
}
I have written code in C#
void printDiagonally(int max_int)
{
if (max_int < 0)
return;
int row_incrementer = 1;
int row_start = 1;
while (row_start <= max_int)
{
int col_incrementer = row_incrementer;
int col_value = row_start;
while (col_value <= max_int)
{
Console.Write("{0} ", col_value);
col_value += col_incrementer;
col_incrementer++;
}
Console.WriteLine();
row_incrementer++;
row_start += row_incrementer;
}
static void Main(string[] args)
{
const int DIVIDER = 3;
const int MAX_DIGITS = 3;
const char BYTES = 'B';
const char KILOBYTES = 'K';
const char MEGABYTES = 'M';
const char GIGABYTE = 'G';
// Get the input from the console
string stringInput = Console.ReadLine();
// Extract the bytes from the input
char lastChar = stringInput[stringInput.Length - 1];
string stringBytes = stringInput.Substring(0, stringInput.Length - 1);
// Get the length of the input bytes
int lengthBytes = stringBytes.Length;
// If the length of input bytes is less than 3 digits,
// output is same as input
// E.G. 34K
if (lengthBytes <= MAX_DIGITS)
{
Console.WriteLine("The output is: {0}", stringInput);
return;
}
// Length divided by 3 (10 to the power 3 is the multiple)
// Decides if it is KB, MB or GB
int quotient = (lengthBytes - 1)/ DIVIDER;
// Length modulo 3 decides where the decimal is placed
int modulo = lengthBytes % DIVIDER;
char unit = 'O';
switch (quotient)
{
case 0:
unit = BYTES;
break;
case 1:
unit = KILOBYTES;
break;
case 2:
unit = MEGABYTES;
break;
case 3:
unit = GIGABYTE;
break;
}
// Modulo 0 means no decimal required
// It is a multiple of 3
int max = (modulo == 0) ? MAX_DIGITS : modulo;
string result_dec = stringBytes.Substring(0, max);
if (result_dec.Length == MAX_DIGITS)
{
Console.WriteLine("The output is: {0}", string.Concat(result_dec, unit));
return;
}
// Add the decimal after the digits
string result = string.Concat(result_dec, '.', stringBytes.Substring(max , MAX_DIGITS - max), unit);
Console.WriteLine("The output is: {0}", result);
return;
}
struct Node
{
int data;
Node* left;
Node* right;
Node* parent;
};
Node* RightNeighbor(Node* node)
{
if(!node)
return node;
uint level = 1;
Node* currParent = node->parent;
while(currParent)
{
Node* temp = GetLeftMostChild(currParent->right, level-1);
if(temp)
return temp;
++level;
currParent = currParent->currParent->parent;
}
return null;
}
Node* GetLeftMostChild(Node* node, uint level)
{
if(0 == level)
return node;
if(node->left)
return GetLeftMostChild(node->left, level-1);
if(node->right)
return GetLeftMostChild(node->right, level-1);
return null;
}
Really stumped me. So I started with O(n^2) solution:
int GetSum()
{
int sum = 0;
// Get values from all nodes prior it self
for(int i = 0; i < id; ++i)
{
sum + = recv(i);
}
// Send self value to all prior to self
for(int i = 0; i < id; ++i)
{
send(i, val);
}
// Send self value to all after self
for(int i = id+1; i < N; ++i)
{
send(i , val);
}
// Get values from all after self
for(int i = id+1; i < N; ++i)
{
sum+= recv(i);
}
return sum+val;
}
Then I realized it can be done in O(n):
#define SERVER = 0
int GetSum()
{
int sum =0;
if(id == SERVER)
{
for(int i = 1; i< N; ++i)
{
sum + = recv(i);
}
sum += val;
for(int i = 1; i < N; ++i)
{
send(i, sum);
}
return sum;
}
send(SERVER, val);
return recv(SERVER);
}
But he wanted better. After multiple clues, it was clear that since the IDs of the Nodes are sorted and in sequence from 0 to N-1, we can consider the nodes as tree, with 0 as root and the children of a Node will be (2*ID+1) parent would (ID-1)/2.
And we can take a recursive Binary approach.
int GetSum()
{
// break condition
if(2*id + 1 > N-1 )
{
send((id-1)/2, val);
sum = recv((id-1)/2);
return sum;
}
// recurse
int sum = val + recv(2*id + 1) + recv(2*id + 2);
// send to parent:
if(id !=0)
{
// send partial sum to parent
send((id-1)/2, sum);
// receive full sum from parent
sum = recv((id-1)/2);
}
// Send final sum to children
send(2*id + 1, sum);
send(2*id + 1, sum);
}
@Mystic
Only the function signature was provided. He didn't provide the function itself.
I had to code the solution without the code for send and receive.
I am curious as to how will it help to know the code for send and receive? Will help me improve my understanding.
Thanks.
These are three solutions I implemented:
Solution 1 with HashTable:
//Global vairable
Hashtable<int, int> myHasTable = new Hashtable<int, int>();
void PopulateHashTable(int[] array1, int[] array2)
{
foreach(int i in array1)
{
if(myHasTable(i).Value == 10)
continue;
myHasTable(i).Value = 10;
}
foreach(int i in array2)
{
if(myHasTable(i).Value==1 || myHasTable(i).Value==11)
continue;
myHasTable(i).Value++;
}
return;
}
int[] Union(int[] array1, int[] array2)
{
int[] unionArray = new int[array1.length + array2.length];
int index = 0;
foreach(int i in array1)
{
if(myHasTable(i).Value > 1)
{
unionArray[index++] = i;
}
}
foreach(int i in array2)
{
if(myHasTable(i).Value == 1)
{
unionArray[index++] = i;
}
}
return unionArray;
}
int[] Intersection(int[] array1, int[] array2)
{
int[] intersectionArray = new int[array1.length, array2.length];
int index= 0;
foreach(int i in array1)
{
if(myHasTable(i) == 11)
intersectionArray[index++] = i;
}
return intersectionArray;
}
No extra memory O(n^2) Union only:
// No extra memory Union function
int[] Union(int[] array1, int[] array2)
{
int unionArray = new int[array1.length, array2.length];
int index = 0;
int runner = 0;
unionArray[index++] = array1[0];
foreach(int i in array1)
{
runner = 0;
while(runner < index)
{
if(uninoArray[runner] != i)
{
runner++;
}
else
{
break;
}
}
if(runner == index)
{
unionArray[index++] = i;
}
}
// Repeat for array2
// Sorted arrays union
// Sorting takes O(log n) time.
// Assume array1 and array2 are sorted
int[] Union (int[] array1, int[] array2)
{
int unionArray;
index1 = 0;
int index2 = 0;
//unionArray[index++] = array1[0]
foreach(int i = 0; i < array1,length + array2.legnth; ++i)
{
if(array1[index1] == array2[index2])
{
if(index > 0 && array1[index1] != unionArray[index-1])
{
uninoArray[index++] = arra1[index1];
index1++;
index2++;
}
}
else if(array1[index1] < array2[index2])
{
unionArray[index++] = array1[index1++];
}
else
{
unionArray[index++] = array2[index2++];
}
}
}
Test cases:
1. Unsorted array with single value, all duplicates
2. Unsorted array some duplicates
3. Unsorted array no dupes
4. One array, 2nd empty
5. Sorted array, multiple dupes
6. Sorted array no dupes
7. Very large arrays
8. Both are empty arrays
9. 1 valued array(s)
10. Negative value and + values
11. both arrays with exactly same values
12. both arrays with unique values only
13. both large arrays containing only one value, duped
No specification about extra space so I propose using a stack.
Node* LowestCommonAncestor(Node* node1, Node* node2)
{
if(!node1 && !node2)
return null;
if(!node1 || !node2)
// Ask interviewer what needs to be returned here.
Stack<Node*> s1 = new Stack<Node*>();
Stack<Node*> s2 = new Stack<Node*>();
Node* temp = node1;
while(temp)
{
s1.push(temp);
temp = temp->parent;
}
temp = node2;
while(temp)
{
s2.push(temp);
temp = temp->parent;
}
// Nodes from different trees
if(s1.peek != s2.peek)
return null;
while(s1.peek == s2.peek)
{
temp = s1.pop;
s2.pop;
}
return temp;
}
Queue SerializeBT(TreeNode* root)
{
Queue<Node*> q = new Queue<Node*>();
if(!root)
q.enqueue(root);
else
SerializeBT(root, q);
return q;
}
void SerializeBT(TreeNode* node, Queue q)
{
if(!node)
{
q.enqueue(node);
return;
}
q.enqueue(node);
SerializeBT(node->left, q);
SerializeBT(node->right, q);
return;
}
@DashDash,
They way i thought about it is, if the videosize is 2 hours long and your timestamp indicates that you have hit play more than Threshold times on this video within the timestamp span of 2 hours then it means you have issues.
Makes sense?
That is the way I am incrementing the count on the video in my list
But i guess i didnot consider re-viewing of the video.
Create a dictionary with Key as CustomerId (always unique) and value as a LinkList, whose each node represents the videoDetails (structure shown below):
We will have to update the LinkList Add function to do this:
1. Traverse the list and if videoId doesnt exist, create one at tail with count as 1
2. If videoId exists increment count
Traverse through each entry in the dictionary and if the number of play hit doesnt meet or exceeds the threshold, remove the node.
Return the dictionary
Struct VideoDetails
{
VideoID vID;
VideoLength vLength;
uint numberOfPlayHits;
}
@Artist,
Good approach.I have a question though:
Worst case scenario (lets say the right most leaf and its parent form the sum), you will traverse the whole tree and search the whole tree for val correct? which would make it O(n^2) ?
My implementation of your algorithm ...
struct Node
{
int data;
Node* left;
Node* right;
}
Driver Function
bool FindSum(Node* root, int sum, Node* node1, Node* node2)
{
node1 = NULL;
node2 = NULL;
if(!root)
return false;
Node* current = root;
while(current && current->data > sum)
current = current->left;
if(!current)
return false;
FindSum(current, current, sum, node1, node2);
if(!node1)
return false;
return true;
}
Recursive Function to do a In-Order traversal
void FindSum(Node* root, Node* current, int sum, Node* node1, Node* node2)
{
int value = sum - current->data;
if(FindNode(root, value, node2))
{
node1 = current;
return;
}
if(current->left)
FindSum(root, current->left, sum, node1, node2);
if(current->right)
FindSum(root, current->right, sum, node1, node2);
}
Helper Function to find a node with given data
bool FindNode(Node* root, int data, Node* node)
{
if(!root)
return false;
while(root)
{
if(root->data == data)
{
node = root;
return true;
}
else if(root->data < data)
root = root->right;
else
root = root->left;
}
return false;
}
@DashDash,
I also thought the same during the interview. But the interviewer posed an example where the int variable wasn't sufficient. I can't remember the example right now. I am trying to remember\find it. Will udpate as soon as I do.
But yes you are correct int will work for most cases.
int LevelWithMaxNodes(Node* root)
{
if(!root)
return -1;
int maxNodes = 1;
int runningMaxNodes = 1;
int level = 1;
int runningLevel = 1;
Queue<Node*> myQ = new Queue();
Node* DELIMITER = null;
myQ.push(root);
myQ.push(DELIMITER);
while(!myQ.IsEmpty())
{
Node* current = myQ.dequeue();
if(current)
{
++runningMaxNodes;
// The below condition returns the first Level with max nodes, >= will give the last level with maxNodes
if(runningMaxNodes > maxNodes)
{
maxNodes = runningMaxNodes;
level = runningLevel;
}
if(current->left)
myQ.enqueue(current->left);
if(current->right)
myQ.enqueue(current->right);
}
else if(current == DELIMITER)
{
++runningLevel;
myQ.enqueue(DELIMITER);
}
}
return level;
}
Every time I dequeue a NULL (delimiter) I push a delimiter.
When 1 is queued in, I queued a NULL PTR as a delimiter. After which 2 & 3 got queued in followed by a NULL delemiter.
So when I dequeue 3, the front of the queue should be a null. So I will make the RightNeighbor of 3 as NULL. As expected.
This was my attempt, which the interviewer approved. Please let me know if i missed something.
Thanks.
struct Node
{
int data;
Node* left;
Node* right;
}
Use Iteration
Node* FindCeiling(Node* head, int key)
{
if(!head)
return head;
Stack<Node*> myStack = new Stack();
Node* current = head;
while(current)
{
if(current->data > key)
{
myStack.push(current);
current = current->left;
}
if(current->data <= key)
current = current->right;
}
return myStack.Pop();
}
Use Recursion
Node* FindCeiling(Node* head, int key)
{
if(!head)
return head;
if(head->data <= key)
return FindCeiling(head->right, key);
Node* temp = FindCeiling(head->left, int key);
if(!temp)
return head;
return temp;
}
struct Node
{
int data;
Node* right;
Node* left;
Node* RightNeighbor;
}
void UptateTreeToPointToRightNeighbor(Node* head)
{
if(!head)
return null;
Queue<Node*> myQ = new Queue();
myQ.push(head);
myQ.push(NULL);
while(!myQ,IsEmpty)
{
Node* curr = myQ.Dequeue();
if(curr)
{
curr->RightNeighbor = myQ.Front;
if(curr->left)
myQ.push(curr->left);
if(curr->right)
myQ.push(curr->right);
}
else
myQ.push(NULL);
}
}
Class Player
{
public:
void play(string bandName, string songName);
string topSong(string bandName);
private:
Hash<string bandName, Class Band> bands = new Hash<string, Class Band>();
}
Class Band
{
public:
string Name;
void play(string songName);
string topSong();
private:
Hash songs = new <string songName, Song songs>();
// Will ensure that the topSong variable is updated by one thread at a time
volatile song topSong;
}
Class Song
{
public:
Song song;
void IncrementRequest();
int GetNumberofRequests();
private:
int numberOfRequests; // initialized to 0 in the constructor
}
string topSong()
{
return this.topSong;
}
void play(string SongName)
{
// Assuming that in case of same number of plays, the latest song wins
if (topSpong.GetNumberOfRequests <= (song.GetNumberOfRequests + 1))
{
topSong = song;
}
song.incrementRequest();
song.play();
}
void IncrementRequest()
{
this.numberOfRequests++;
}
int GetNumberOfRequests()
{
return numberOfRequests;
}
Rep
RepGayle L McDowell, CEO at CareerCup
Gayle Laakmann McDowell is the founder / CEO of CareerCup, which provides programming interview prep for candidates interviewing with Microsoft, Google ...
RepA passionate hard-core programmer.
RepRussBDycus, Android test engineer at ABC TECH SUPPORT
I am working as a manager in Lionel Kiddie City company. I really enjoy my job. I like to play ...
Rep
RepWilliamDGiles, Cloud Support Associate at ADP
Spent 2001-2006 creating marketing channels for tar worldwide. Was quite successful at building tobacco for farmers. Won several awards for ...
Rep
Repemilymross903, Area Sales Manager at ASAPInfosystemsPvtLtd
Hello, I am Emily and I live in Liberty. I am working as Fitness trainers and I instructors lead, instruct ...
Repjoycepwise, Blockchain Developer at Accenture
Hello, I’m Joyce. I’m a business developer living in Tampa, FL. I am a fan of music, travel ...
Rep
RepGet powerful wazifa to know who did black magic. Guru Ji is the master of black magic totke, kala jadu ...
- JSDUDE April 19, 2017