aonecoding
 1of 1 vote
Answercreate a class of integer collection,
 aonecoding in United States
3 APIs:
append(int x),
get(int idx),
add_to_all(int x)，
in O(1) time。
Followup:
implement
multiply_to_all(int x)
e.g.
insert(1)
insert(2)
add_to_all(5)
insert(3)
get(0) > returns 6
get(2) > return 3
multiply_to_all(10)
insert(4)
get(1) > returns 70
get(2) > returns 30
get(3) > returns 4 Report Duplicate  Flag
Google Software Engineer Algorithm  0of 0 votes
AnswerLonely Pixel
 aonecoding in United States
Given an N x M image with black pixels and white pixels, if a pixel is the only one in its color throughout its entire row and column, then it is a lonely pixel. Find the number of lonely pixels in black from the image. (O(NM)) Report Duplicate  Flag
Google Software Engineer Algorithm  1of 1 vote
AnswerTweet Recommendation
 aonecoding in United States
Twitter Interview Online Test
On Twitter, millions of tweets are posted on a daily basis. Help Twitter write a simple ranking algorithm to find the best of all tweets. It works as follows: A good tweet receives many “likes” from people on Twitter, either from people you follow, or people you do now follow. A tweet is more relevant to you if people you follow also liked the tweet. If enough people you follow have liked that tweet, we recommend that tweet to you.
Your task is to complete the function
getRecommendedTweets(followGraph_edges, likeGraph_edges, targetUser, minLikeThreshold), which returns a list of tweet IDs in sorted order that should be recommended for a certain user. It takes 4 parameters:
followGroup_edges stores follow relationships as an array of tuple of integers.
For example, followGraph_edges = Array{(A, B), (A, C), (B, C)} represents 3 follow relationships:
A follows B
A follows C
B follows C
likeGraph_edges stores like relationships, also in an array of tuple of integers.
For example, likeGraph_edges = Array{(A, T1), (B, T2), (A, T2)} means:
A liked tweet T1
B liked tweet T2
A liked tweet T2
targetUser is the user ID for which we generate recommended tweets
minLikeThreshold is the minimum number of likes a tweet mush receive from people you follow to be recommended
For example, if minLikeThreshold = 4, only tweets that received at least 4 likes from people you follow should be recommended
Note: If you cannot find a single tweet that meets our requirement, simply return an empty list. You may also use any functions provided by the standard library. Report Duplicate  Flag
Twitter Software Engineer Algorithm  0of 0 votes
AnswersEmployees Per Department
 aonecoding in United States
Twitter Interview Online Test SQL
A company uses 2 data tables, Employee and Department, to store data about its employees and departments.
Table Name: Employee
Attributes:
ID Integer,
NAME String,
SALARY Integer,
DEPT_ID Integer
Table Name: Department
Attributes:
DEPT_ID Integer,
Name String,
LOCATION String
View sample tables:
https://s3uswest2.amazonaws.com/aonecode/techblog/50cfcdd1d61f1bd6002cf4d3b4a61debmin.jpeg
Write a query to print the respective Department Name and number of employees for all departments in the Department table (even unstaffed ones).
Sort your result in descending order of employees per department; if two or more departments have the same number of employees, then sort those departments alphabetically by Department Name. Report Duplicate  Flag
Twitter Software Engineer SQL  2of 2 votes
AnswerHacking Time
 aonecoding in United States
Twitter Interview Online Test
Alice and Bob are avid Twitter users and tweet to each other every day. One day, Alice decides to send Bob a secret message by encrypting it and tweeting it publicly to Bob. They had anticipated a scenario like this, and exchanged a shared secret key some time in the past. Unfortunately, Alice isn’t very familiar with encryption algorithms, so she decides to make her own. Her encryption algorithm works as follows:
1. Choose a key entirely composed of digits 0  9, for example: 12345.
2. Iterate each letter of the plaintext message and rotate the letter forward a number of times equal to the corresponding digit in the key. If the rotation of the letter passes Z, start back at A.
3. If the message is longer than the key, loop back to the first digit of the key again, as many times as needed.
4. If a nonalphabetical character is encountered, leave it as it is and don’t move to the next digit in the key.
5. Characters should maintain their upper or lowercase orientation after rotation.
Here is an example message and its encrypted output using Alice’s algorithm:
Original message: Hi, this is an example
Example Key: 4071321
Encrypted message: Li, ailu jw facntll
Where H was rotated forward 4 letters to L, i rotated 0 to i, t rotated forward 7 letters to a, etc.
Satisfied with the security of her algorithm, Alice tweets the following ciphertext to Bob:
Otjfvknou kskgnl, K mbxg iurtsvcnb ksgq hoz atv. Vje xcxtyqrl vt ujg smewfv vrmcxvtg rwqr ju vhm ytsf elwepuqyez. Atvt hrqgse, Cnikg
Uh oh! Unfortunately for Alice and Bob, you are “Eve”, the world’s greatest hacker. You’ve been intercepting Alice’s messages for some time now, and know she always ends her messages with the signature “Your friend, Alice”. You job is now as follows:
Determine the key Alice is using.
Using this key, write a function to decrypt any future communications from Alice. This method should take the encrypted string as an input and return the original unencrypted string. Report Duplicate  Flag
Twitter Software Engineer Algorithm  1of 1 vote
AnswerIII. Square root of a number?
 aonecoding in United States
IV. Expression operators? Add signs (+, , *, /) to a string to form target
V. Top trending posts in last 5m, 1H, 1Day? Report Duplicate  Flag
Linkedin Software Engineer Algorithm  0of 0 votes
AnswerI. Closest K nodes to a target in BST? (Do it in O(n)?)
 aonecoding in United States
II. Nested List sum? Report Duplicate  Flag
Linkedin Software Engineer Algorithm  0of 0 votes
AnswerSolve the 24 Game
 aonecoding in United States Report Duplicate  Flag
Twitter Software Engineer Algorithm  3of 3 votes
AnswersRound4
 aonecoding in United States
Starting from num = 0, add 2^i (where i can be any nonnegative integer) to num until num == N. Print all paths of how num turns from 0 to N.
For example if N = 4,
Paths printed are [0,1,2,3,4], [0,1,2,4], [0,1,3,4], [0,2,4], [0,2,3,4], [0,4].
[0,2,4] is made from 0 + 2^1 + 2^1. [0,1,3,4] from 0 + 2^0 + 2^1 + 2^0 Report Duplicate  Flag
Google Software Engineer Algorithm  2of 2 votes
AnswersRound3
 aonecoding in United States
For N light bulbs, implement two methods
I. isOn(int i)  find if the ith bulb is on or off.
II. toggle(int start, int end) Report Duplicate  Flag
Google Software Engineer Algorithm  2of 2 votes
AnswersRound1
 aonecoding in United States
Find if two people in a family tree are bloodrelated.
Round2
Given some nodes in a singly linked list, how many groups of consecutively connected nodes there is.
For linked list
0>1>2>3>4>5>6,
given nodes 1, 3, 5, 6
there are 3 groups [1], [3], and [5, 6]. Report Duplicate  Flag
Google Software Engineer Algorithm  4of 4 votes
AnswersGiven a sorted array A, find how many subsets of A satisfies MIN(subset) + MAX(subset) < K.
 aonecoding in United States Report Duplicate  Flag
Facebook Software Engineer Algorithm  1of 1 vote
AnswersRound 5:
 aonecoding in United States
Given a set of synonyms such as (fast, quick), (fast, speedy), (learn, study), decides if two sentences were synonymous.
(The sentences were structurally the same and has the same number of words in them.
The synonymous relation [fast ~ quick] and [fast ~ speedy] does not necessarily mean [quick ~ speedy].)
Followup:
If the synonymous relation passes down so that [fast ~ quick] and [fast ~ speedy] implies [quick ~ speedy], decide if two sentences were synonymous. Report Duplicate  Flag
Google Software Engineer Algorithm  1of 1 vote
AnswersRound 4:
 aonecoding in United States
Implement a class Employment with these 3 methods: assignManager(p1, p2): assign p1 as p2's manager. beColleague(p1, p2): make p1 and p2 peer colleagues. isManager((p1, p2): decide if p1 is the manager of p2. Report Duplicate  Flag
Google Software Engineer Algorithm  2of 2 votes
AnswersRound 3
 aonecoding in United States
Given a matrix of 0s and 1s where 0 is wall and 1 is pathway, print the shortest path from the first row to the last row.
Can walk to the left, top, right, bottom at any given spot.
Followup:
If every pathway takes a cost (positive integer) to get through, print the minimum cost path from the first row to the last row. Report Duplicate  Flag
Google Software Engineer Algorithm  1of 1 vote
AnswersGoogle onsite June
 aonecoding in United States
Round 1
Leetcode 10
Round 2
Select a random point uniformly within a rectangle, (The side of rectangle is parallel to the x/ y grid).
Followup: Given multiple nonoverlapped rectangles on the 2D grid, uniformly select a random point from the rectangles. Report Duplicate  Flag
Google Software Engineer Algorithm  2of 2 votes
AnswersPhone Interview Amazon, Seattle
 aonecoding in United States
I. Get the sum of all prime numbers up to N. primeSum(N).
Followup: If primeSum(N) is frequently called, how to optimize it.
II. OODesign Parking Lot Report Duplicate  Flag
Amazon Software Engineer Algorithm  2of 2 votes
AnswersApple Map Team
 aonecoding in United States
1. Given an array A and some queries, query(i, j) returns the result of Ai*...*Aj, in other words the multiplication from Ai to Aj.
The numbers in A are nonnegative.
Implement query(i, j).
2. Flatten nested linked list
3. POI search design
4. LC238 & LC279 Report Duplicate  Flag
Apple Software Engineer Algorithm  1of 1 vote
AnswersAirbnb Interview
 aonecoding in United States
Min cost of flight from start to end if allowed at most k transfers.
Given all the flights in a string:
A>B,100,
B>C,100,
A>C,500,
If k = 1，from A to C the best route is A>B>C at the cost of 200. Report Duplicate  Flag
Airbnb Algorithm  3of 3 votes
AnswersApple phone interview
 aonecoding in United States
Given an API to find all IPv4 addresses in a log file, find all IPs that occurred only once.
Followup: What if the log comes from a data stream.
Followup: If the machine has 4GB RAM, is there going to be a problem? Report Duplicate  Flag
Apple Backend Developer Algorithm  2of 2 votes
Answer4/5 Round at Uber
 aonecoding in United States
Coding: Given a 2D array of either '\' or '/', find out how many pieces this rectangle is divided into graphically.
For a 2X2 matrix with
/\
\/
The matrix split into 5 pieces  the diamond in middle and the four corners. Return 5 as the answer.
5/5 Round at Uber
Design Excel. Report Duplicate  Flag
Uber Software Engineer Algorithm  1of 1 vote
Answers2/5 Round at Uber
 aonecoding in United States
Bar raiser  Behavioral questions. Coding: Find if a set of meetings overlap. Meeting has a starttime and an endtime with accuracy to minute. All meetings take place in the same day. Do this in O(n) time.
3/5 Round at Uber
Coding: Subset sum. Followup: Optimize the solution. Report Duplicate  Flag
Uber Software Engineer Algorithm  0of 0 votes
Answers1/5 Round at Uber
 aonecoding in United States
Manager : Behavioral questions. Basic system design concepts. Publish/subscribe model. Discussion on Uber architecture. Report Duplicate  Flag
Uber Software Engineer System Design  2of 2 votes
AnswerUber
 aonecoding in United States
1. Mirror Binary Tree
2. String pattern matching
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(String str, String pattern)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa","a{1,3}") → true
isMatch("aaa","a{1,3}") → false
isMatch("ab","a{1,3}b{1,3}") → true
isMatch("abc","a{1,3}b{1,3}c") → true
isMatch("abbc","a{1,3}b{1,2}c") → false
isMatch("acbac","a{1,3}b{1,3}c") → false
isMatch("abcc","a{1,3}b{1,3}cc{1,3}") → true
In pattern string, a char followed by {lower, upper} means that the char occur lower to upper(exclusive) times. e.g. a{1, 3} > a occurs 1 or 2 times. Report Duplicate  Flag
Uber Software Engineer Algorithm  3of 3 votes
Answers3.1 design: design fb inbox search —> just focus on the post
 aonecoding in United States
4.1 binary tree to circular double linked list.
4.2 two arrays, find the common elements of two sorted array. if one array is small, the other is very big. Report Duplicate  Flag
Facebook Software Engineer Algorithm  2of 2 votes
Answers2.1 career discussion
 aonecoding in United States
2.2 divide two numbers with no / or % Report Duplicate  Flag
Facebook Software Engineer Algorithm  4of 4 votes
Answers1/4 round of FB onsite interview, Master Degree, Hired
 aonecoding in United States
1.1 diameter of tree
1.2 find the point which have the maximum overlap of intervals Report Duplicate  Flag
Facebook Software Engineer Algorithm  3of 3 votes
Answers1 year exp. Interviewed at Cambridge, MA
 aonecoding in United States
Round1
LC304. Followup: given a char stream instead a string as the input, get the longest substring with at most K distinct characters.
Round2
Find out the area of a number of squares on a plane, an advanced version of LC223.
Had no clue on that problem at all so the interviewer kindly gave another one LC305.
Round3
Similar to LC393 but the interviewer made a slightly different rule for encoding.
Followup: decode with utf16. It took quite a while for me to understand the rules.
Round4
Card game rule: the hand is drawn from a pack of cards (no jokers).
Play cards ONLY when they are
1. 3 of a kind ('AAA' ) or 4 of a kind('AAAA’).
2. a straight flush of 3 or more cards('JQK' or 'A23456...' in the same suit).
Find out whether the player is able to play the whole hand given.
e.g. [Spade A, Spade K, Spade Q, Diamond Q, Heart Q] return false.
[Spade A, Spade K, Spade Q, Diamond Q, Heart Q, Club Q] return true. Report Duplicate  Flag
Google Software Engineer Algorithm  3of 5 votes
AnswersMaster Degree 2 year exp
 aonecoding in United States
1st Round.
Behavioral  most challenging project.
Tech  bit manipulation
2nd Round. A matrix has 0s and 1s only.. All the 1s in every row are to the of 0s. Find out the leftmost 1 in the entire matrix.
3rd Round.
A dp problem.
Find out how many ways you can make change of N cents given coins of values [a1, a2, a3...], each type of coin got infinite supplies.
Arrangement of coins don't matter.
4th Round.
Design news feed.
A user wrote a post with the basic user info, pictures and time etc (I even drafted a basic UI on whiteboard).
How to obtain these information and store them.
If a new feature with a button is added. How to maintain availability of old service to users who did not update the app.
Did not dive further into scaling.
5th Round.
User groups  If I made a certain post visible to a user group, how to store the post? how to push the post to the chosen group. If there are new friends who aren't assigned to any group just yet, how to treat them as if they were in the same 'unassigned' group?
DB sharding is involved.s Report Duplicate  Flag
Facebook Software Engineer System Design  2of 2 votes
AnswersFind the length of longest arithmetic progression in array.
 aonecoding in United States
For example, in the array {1, 6, 3, 5, 9, 7}, the longest arithmetic sequence is 1, 3, 5, and 7 Report Duplicate  Flag
Facebook Software Engineer Algorithm  3of 3 votes
AnswersGoogle fulltime phD candidate w/ work experience.
 aonecoding in United States
Q1. On a 1 meter walkroad, randomly generate rain. The raindrop is 1 centimeter wide.
Simulate how raindrops cover the 1 meter [0~1] road. How many drops does it take to fully cover the 1meter?
Q2. Find out the maximum number of isosceles triangles you can make from a plane of points(cannot reuse points)
Q3.Longest holiday  Every city has a different days of holidays every week. You may only travel to another city at the weekends. What is the max days of holiday you can get this year.
Q4.
Design merchandising product data storage service Report Duplicate  Flag
Google Software Engineer Algorithm  5of 5 votes
AnswersGoogle Onsite in May
 aonecoding in United States
Create a class with a collection of integers.
Enable 3 APIs:
void append(int x),
int get(int idx),
void add_to_all(int x)，//add x to all numbers in collection
These methods should run in O(1) time.
Followup
In addition, implement
void multiply_to_all(int x)
The same required to run in O(1) time Report Duplicate  Flag
Google Software Engineer Algorithm  1of 1 vote
AnswersImplement circular buffer with read & write functions
 aonecoding in United States Report Duplicate  Flag
Facebook Software Engineer Data Structures  1of 1 vote
AnswersCoding III
 aonecoding in United States
Implement int divide(int a, int b) without division or mod operation.
## Round IV
Behavioral Questions + Project Walk Through + Coding (Validate BST)
## System Design V
Design memcache to enable read, write and delete (single server, nondistributed infrastructure).
Which data structure to go with?
Eviction rules?
How to minimize segmentation?
How to handle concurrency?
## Extra
After two weeks they called me to an extra round of system design.
How to store social graphs?
How to handle concurrent read/write requests(read heavy) on one server. Report Duplicate  Flag
Facebook Software Engineer  0of 0 votes
AnswersCoding I
 aonecoding in United States
Flatten a linked list.
Each node in the list carries a piece of data and a pointer. The data could be in a normal data type such as an integer, or a pointer that points to another list node.
The interviewer gave no specification on how the list node class was defined. You may look at each list node as if it has two pointers  one of them points to the next node; the other points to the ‘data’ which could be either a node or an integer. There also needs to be a function to tell you about the node data is actual data or a pointer.
I solved the problem with recursion. During the process, any nodes that don’t carry an integer get removed. Report Duplicate  Flag
Facebook Software Engineer Algorithm  2of 2 votes
AnswersFB onsite two weeks ago last round of coding . (This problem is also in the internal question bank of G.)
 aonecoding in United States
There is a robot in a room. The initial location of the robot is unknown. The shape or area of the room is unknown.
You have a remote that could walk the robot into any of the four directions  up, left, down or right.
Here is the move method: boolean move(int direction), direction: 0, 1, 2, 3. If the robot hits the wall, the method returns false.
Otherwise returns true and the robot moves on to the direction given.
Find out the area of the room.
e.g.
X
XXX X
XXXXX 'X' marks the floor plan of the room.
A room like such has an area of 10. Report Duplicate  Flag
Facebook Software Engineer Algorithm  1of 1 vote
AnswersLast Monday phone interview of G.
 aonecoding in United States
Given a vector/list of doubly linked list pointers (a pointer is the directed linkage of two nodes), count how many independent blocks of linked lists there are for the pointers given. Report Duplicate  Flag
Google SDE1 Algorithm  2of 2 votes
AnswerApple Onsite at Cupertino
 aonecoding in United States
Team Data Warehousing
Questions on Hadoop, Hive and Spark
I. Given a table with 1B of user ID and product IDs that the users bought, and another table with product ID mapped with product name. We are trying to find the paired products that are often purchased together by the same user, such as wine and bottle opener, chips and beer … How to find the top 100 of these coexisted pairs of products. If going with hadoop, where is the bottleneck and how to optimize?
II. Someone put distribute Random()*ID in a Hive script to prevent data skew. What would be the problem here? Report Duplicate  Flag
Apple SDE3 design  1of 1 vote
AnswersApple Onsite at Cupertino
 aonecoding in United States
Team Data Warehousing
III. Given three letters ABC, where AB>C, AC>B, BC>A (sequence doesn’t matter). Get the length of the path to convert from a given string to a single character.
For example, “ABACB” goes to “ACCB” (based on AB >C, convert s[1] and s[2] to C)
“ACCB” goes to “BCB” (based on AC>B)
“BCB” goes to “AB”
“AB” goes to “C”
So it takes 4 steps to change the given string into a single character.
If a given string cannot be resized to 1 character, such as “AAA” or "ABACABB", return 1. Report Duplicate  Flag
Apple SDE3 Algorithm  0of 0 votes
AnswersApple Onsite at Cupertino
 aonecoding in United States
Team Data Warehousing
There were 6.5 rounds in total, that 0.5 on package negotiation with the HR and the remaining rounds with 2 managers and 4 engineers.
Only three pure coding questions were asked.
I. Use a stack to sort given data.
II. Given an array with positive integers only, find the MIN integer that is missing from the array. Report Duplicate  Flag
Apple SDE3 Algorithm  0of 2 votes
AnswersAmazon SDE 2 Onsite (1 of 4 Rounds)
 aonecoding in United States
In a file system stored a large amount of user’s browsing data, including the urls that the user visited. Design a function that outputs the longest common path of all the urls.
Having finished the code, I was asked to analyze the complexity. Report Duplicate  Flag
Amazon Software Engineer Algorithm  2of 2 votes
AnswersAmazon SDE 2 Onsite (4 of 4 Rounds)
 aonecoding in United States
Assume that there is an ebook application. For every book the sharable part of the book content cannot exceed 10% of the whole book. Design a module to decide whether the current part of content is sharable.
The description given is vague. I had to push him with questions to give the details.
At first I thought the problem was about strStr. But then the interviewer said that even if there are two paragraphs of the book content with the exact same texts, as long as they are not in the same place, they would be considered different content.
I then realized it’s a question about merging segments  have a helper to find each pair of start and end point of the input content (given multiple separated paragraphs). Then merge the intervals and see if they combined exceed 10% of the entire book.
The interviewer approved my solution and ask me to code it.
Overall I feel like that the Amazon SDE II Interview doesn’t focus on just algorithm. It’s more about problem solving in practice and then implement the only core function on whiteboard. Report Duplicate  Flag
Amazon Software Engineer  1of 1 vote
AnswersVMWare Standard Online Screen
 aonecoding in United States
3rd Question Given an array of strings and a long description about the formatting of IPv6 and IPv4 (it took me more than 5 minutes to read the description). Write a function to find if a string is IPv4 or IPv6 address or neither.
4th Question Given an integer array, whenever a duplicate number is found, you may increment it (++). Find the minimum sum of the numbers in the array by keep incrementing the dups until all the numbers are unique. Report Duplicate  Flag
VMWare Inc Software Engineer Algorithm  2of 2 votes
AnswerVMWare Standard Online Screen
 aonecoding in United States
The Online Assessment was called something like Life Cycle Challengeqpan.
There are 4 questions in total given 60 minutes. The problem description was unexpectedly long that it takes 5 minutes just to read a question.
1st Question Design a function to create BST. Given an integer array, insert the integers into the binary search tree and print all the steps taken.
2nd Question Given an integer, print the index of all the positions in which the binary bit is 1 in order. Report Duplicate  Flag
VMWare Inc Software Engineer Algorithm  5of 5 votes
AnswersFacebook Senior Engineer Onsite 2017
 aonecoding in United States
1st Round
Question 1: Binary tree to doubly linked list.
Question 2: Read 4 (Given the read4 API, read an entire file)
2nd Round
Culture fit. No coding.
3rd Round
Question: System Design POI (Point of Interest. Given a point, find things within a radius).
Lunch
4th Round
Question 1: Decode way
Question 2: Random max index
5th Round
Question: System design + componentwise design on download manager Report Duplicate  Flag
Facebook Software Engineer Algorithm  5of 5 votes
Answers5th Round
 aonecoding in United States
Openended question What happens when you type a url in the browser and hit enter?
Second question Given an array of integers, print all the numbers that meet the following requirement  when the number is greater than every number on its left and smaller than every number on the right. Report Duplicate  Flag
Google Software Engineer Algorithm  2of 4 votes
Answerinterviewed by senior engineer
 aonecoding in United States
Question Given two strings s1 and s2, combine the characters in the strings and maintain the sequence of characters
Followup If s1 has a length of m and s2 has a length of n, how many ways the strings could be merged. Figure out the formula F(m, n) = ? Report Duplicate  Flag
Google Software Engineer Algorithm  0of 2 votes
AnswersHow to randomly select a number in an array?
 aonecoding in United States
array: [15, 2, 4, 5, 1, 2, 0]
Followup:
Given a second array freq where freq[i] represents the occurrence of the ith number in array, how to randomly select a number in array based on the frequency.
Extra requirement:
Could you complete the selection in a singlepass(go through each array only once)? Report Duplicate  Flag
Linkedin Software Engineer Algorithm  1of 5 votes
AnswersIn school a student gets rewarded if he has an attendance record without being absent for more than once or being late for 3 times continuously.
 aonecoding in United States
Given a student's attendance record represented by a string with 3 possible characters 'L'(Late), 'A'(Absent), 'O' (On time),
check whether the student qualifies for the reward.
e.g.
@INPUT (String) "OLLAOOOLLO"
@RETURN (Boolean) False
The student does not qualify for reward because "LLA" means he was late for 3 times in a row.
@INPUT (String) "OLLOAOLLO"
@RETURN (Boolean) True
Followup:
If known the length of the attendance string is n, how many possible ways there is to attend school and make sure you get the reward. Report Duplicate  Flag
Google Software Engineer Algorithm  0of 0 votes
AnswersIn school a student gets rewarded if he has an attendance record without being absent for more than once or being late for 3 times continuously.
 aonecoding in United States
Given a student's attendance record represented by a string with 3 possible characters 'L'(Late), 'A'(Absent), 'O' (On time), check whether the student qualifies for the reward.
e.g.
@INPUT (String) "OLLAOOOLLO"
@RETURN (Boolean) False
The student does not qualify for reward because "LLA" means he was late for 3 times in a row.
@INPUT (String) "OLLOAOLLO"
@RETURN (Boolean) True
Followup:
If known the length of the attendance string is n, how many possible ways there is to attend school and make sure the student gets the reward. Report Duplicate  Flag
Google Software Engineer Algorithm  3of 3 votes
AnswersEarly on I prefer to post the interview questions with a simplified description or only present the algorithmic part of it. Because it's hard for our students to memorize the full description of a problem. Therefore often times only the algorithm behind the question is given.
 aonecoding in United States
But somehow a user of this site @concernedCoder gets unhappy with it. So from today on, we will try to recover the original version of the question as much as possible.
We assure you all of the questions we posted are real questions that you have a good chance to come across during a coding interview. Anyone who has experience in a coding interview should be able to see that.
Here is the full description of a recent Amazon OA question. The reason why we are able to provide the full description is because it's the online assessment. But for an onsite interview it's almost impossible to recover the questions perfectly.
Title: Item Recommendations
Amazon wants to recommend items to a customer who has just made a purchase. Amazon's recommendation algorithm is based on item 'connection'.
Two items are 'strongly connected' if a single customer bought both of them. Two items are 'weakly connected' if they are both strongly and weakly connected to some other third item.
Your task is to determine the number of the items strongly and weakly connected to a given item.
You are provided the item id represented as a string, as well as the list of customer purchases represented as an array of strings. Each element in the array consists of a customer id(represented as a string) and an item id (also represented as a string). The two ids are separated by a colon. For example, if they element in the array is "ABJA:Z42G" then that means customer ABJA purchased item Z42G.
Your output consists of an array, where the first element in the array represents the number of items strongly connected to the provided item id and the second element represents the number of items weakly connected to the provided item id.
For example, if you were provided with the following input:
determineRecommendation("ABC",["first:ABC", "first:HIJ", "sec:HIJ", "sec:KLM", "third:NOP", "fourth:ABC", "fourth:QRS", "first"DEF", "fifth:KLM", "fifth:TUV"])
You would return the following array:
[3, 2]
since ABC is strongly connected to 3 items: DEF, HIJ and QRS and is weakly connected to 2 items: KLM and TUV
Although the description is long, the problem is just asking for 'search (with either DFS or BFS) in a graph'. Report Duplicate  Flag
Amazon Software Engineer Algorithm  1of 5 votes
AnswersCreate an iterator class that stores a list of the builtin Iterators.
 aonecoding in United States
Implement the next() and hasNext() methods in a Round Robin pattern (pops next element in a circle).
Example:
Given a list [iterator1,iterator2, iterator3...]
when calling RoundIterator.next()
pops iterator1.next if iterator1.hasNext() is true
when calling RoundIterator.next()
pops iterator2.next() if iterator2.hasNext() is true
when calling RoundIterator.next()
pops iterator3.next if iterator3.hasNext() is true
...
when calling RoundIterator.next()
pops iterator1.next if iterator1.hasNext() is true
when calling RoundIterator.next()
pops iterator2.next if iterator2.hasNext() is true
when calling RoundIterator.next()
pops iterator3.next if iterator3.hasNext() is true
...
until there is no more element in any of the iterators Report Duplicate  Flag
Google Algorithm  1of 9 votes
AnswersQ: Weighted meeting room
Given a series of meetings, how to schedule them. Cannot attend more than a meeting at the same time. Goal is to find maximum weight subset of mutually nonoverlap meetings.class Meeting: def __init__(self): self.startTime self.endTime self.weight
@concernedCoder
 aonecoding in United States
When you claim the questions as fake, provide evidence. These are no doubt questions asked in the coding interviews of the best companies and they definitely help interviewees to prepare for the interview.
Why do you have a problem with this? Report Duplicate  Flag
Facebook Software Engineer Algorithm  1of 3 votes
AnswerOn google search, how to enable key word auto completion after a few letters typed.
 aonecoding in United States
Followup: How to rank the words if they are weighted by frequency? Report Duplicate  Flag
Google Software Engineer Algorithm  4of 4 votes
Answers# There's a room with a TV and people are coming in and out to watch it. The TV is on only when there's at least a person in the room.
 aonecoding in United States
# For each person that comes in, we record the start and end time. We want to know for how long the TV has been on. In other words:
# Given a list of arrays of time intervals, write a function that calculates the total amount of time covered by the intervals.
# For example:
# input = [(1,4), (2,3)]
# > 3
# input = [(4,6), (1,2)]
# > 3
# input = {{1,4}, {6,8}, {2,4}, {7,9}, {10, 15}}
# > 11 Report Duplicate  Flag
Facebook Software Engineer Algorithm  5of 5 votes
AnswersFind the median of an unsorted array.
 aonecoding in United States
Have to do better than O(nlogn) time.
e.g.
Given [2, 6, 1] return 2
Given [2, 6, 1, 4] return 3 which is sum of the two elements in middle over 2 Report Duplicate  Flag
Facebook Software Engineer Algorithm  5of 5 votes
Answers/**
 aonecoding in United States
Given many coins of 3 different face values, print the combination sums of the coins up to 1000. Must be printed in order.
eg: coins(10, 15, 55)
print:
10
15
20
25
30
.
.
.
1000
*/ Report Duplicate  Flag
Facebook Software Developer Algorithm  2of 4 votes
AnswersFind all comments in the Java (it could be Python or any other language of your choice) codes that’s parsed in as a string.
 aonecoding in United States
You may assume the codes given is valid.
Input is a single string, e.g.
String codes =
“/* file created by aonecode.com\\n” +
“ welcome to the tech blog*/ \\n” +
“//main method\\n” +
“public static void main(String[] args) { \\n“ +
“ System.out.println(“//welcome”); //output\\n” +
“}”
Output is a list of strings
List<String> ret =
[
“ file created by anecode.com\n welcome to the tech blog”,
“main method”,
“output”
] Report Duplicate  Flag
Google Software Engineer Algorithm  4of 4 votes
AnswersQ: If you were given a series of equations e.g. [A = B, B = D, C = D, F = G, E = H, H = C]
 aonecoding in United States
and then another series [A != C, D != H, ..., F != A ]
Check whether the equations combined is valid.
For the example given, your program should return 'invalid', because the first series implies that A = C, which contradicts the statement A != C in the second series. Report Duplicate  Flag
Amazon Software Engineer Algorithm  3of 3 votes
AnswersPrint first pair of mismatching leaves (first pair as in inorder) given two preorder traversal arrays of BSTs.
e.g.For 5 4 8 2 4 6 9 Preorder Sequence as [5,4,2,4,8,6,9] & 5 3 8 2 4 7 9 Preorder Sequence2 as [5,3,2,4,8,7,9] Print “4, 3”.
@Kart
 aonecoding in United States
If you create the inorder sequences for the two trees, you'll be able to see that 4 and 3 comes far before 6 and 7.
In fact, in any of the three wellknown types of tree traversal, there is NO way for a node in the right tree visited prior to the node in the left tree.
@anon
The question gives just enough detail for you to solve it. It does NOT matter if the trees are balanced or same size. It's said in the first sentence that 'find the first nonmatching pair as in the INORDER sequence', which is the ascending sequence in a BST. Report Duplicate  Flag
Facebook Software Engineer Algorithm  3of 3 votes
AnswersRandomly select one of the weighted items from a linked list. (you may only go through the list once)
 aonecoding in United States
e.g.
weight 1.6 > weight 0.2> ... > weight 3.4
randomly select one item based on the weight. The higher the weight is, the more likely to be selected Report Duplicate  Flag
Amazon Software Engineer Algorithm  3of 3 votes
AnswersGiven a list of system packages, some packages cannot be installed until the other packages are installed. Provide a valid sequence to install all of the packages.
 aonecoding in United States
e.g.
a relies on b
b relies on c
then a valid sequence is [c, b, a] Report Duplicate  Flag
Uber Software Engineer Algorithm  3of 5 votes
AnswersPhone screen Q: String encoding and decoding: Design a method that converts a list of strings into a single string which can be later converted back to the list.
 aonecoding in United States Report Duplicate  Flag
Google Software Engineer Programming Skills  3of 5 votes
AnswersQ: Find the absolute paths to all directories with image files, given a file system that looks like this. The subdirectory is one indent over.
 aonecoding in United States/usr /local profile.jpg /bin config.txt dest.png /rbin image.gif /sys /re /tmp pic.jpg ..... ……
 Report Duplicate  Flag
Google Software Engineer Algorithm  2of 4 votes
AnswersQ: List all comments in the given segment of codes. It's pretty tricky since there is a lot of things to be considered, especially the escape characters.
 aonecoding in United States Report Duplicate  Flag
Google Software Engineer Algorithm

0 Answers
Coding Interview Mentoring
Looking for interview questions sharing and mentors? Visit A++ Coding Bootcamp at aonecode.com (select english at the top right corner).
 aonecoding January 15, 2017
We provide ONE TO ONE courses that cover everything in an interview from the latest interview questions, coding, algorithms, system design to mock interviews. All classes are given by experienced engineers/interviewers from FB, Google and Uber. Help you close the gap between school and work. Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us with any questions. Flag 
0 Answers
Coding Interview Mentoring
Looking for interview questions sharing and mentors? Visit A++ Coding Bootcamp at aonecode.com (select english at the top right corner).
 aonecoding January 15, 2017
We provide ONE TO ONE courses that cover everything in an interview from the latest interview questions, coding, algorithms, system design to mock interviews. All classes are given by experienced engineers/interviewers from FB, Google and Uber. Help you close the gap between school and work. Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us with any questions. Flag
Looking for interview experience sharing and coaching?
Visit AONECODE.COM for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates of FB, LinkedIn, Amazon, Google & Uber etc.)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other toptier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
import java.util.List;
import java.util.ArrayList;
public class IntegerCollection {
List<Integer> collection = new ArrayList<>();
List<Integer> divisors = new ArrayList<>();
int factor = 1;
int addition = 0;
int set0 = 1;
public void append(int x) {
collection.add(x  addition);
divisors.add(factor);
}
public int get(int index) {
if(index >= collection.size()) throw new RuntimeException();
if(divisors.get(index) <= set0) return addition;
return collection.get(index) * (factor / divisors.get(index)) + addition;
}
public void add_to_all(int x) {
addition += x;
}
public void multiply_to_all(int x) {
if(x == 0) {
addition = 0;
factor = 1;
set0 = collection.size()  1;
} else {
addition *= x;
factor *= x;
}
}
}

aonecoding
September 22, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
from collections import defaultdict
def getRecommendedTweets(followGraph_edges, likeGraph_edges, targetUser, minLikeThreshold):
targetUserFollows = {t[1] for t in followGraph_edges if t[0] is targetUser}
recommendedTweets = defaultdict(lambda:0)
for like in likeGraph_edges:
if like[0] in targetUserFollows:
recommendedTweets[like[1]] += 1
return [tweet for tweet in recommendedTweets if recommendedTweets[tweet] >= minLikeThreshold]

aonecoding
September 07, 2017 SELECT
Department.name,
COUNT(Employee.id)
FROM
Department
LEFT JOIN
Employee ON Department.dept_id = Employee.dept_id
GROUP BY
Department.dept_id,
Department.name
ORDER BY
COUNT(Employee.id) DESC,
Department.name
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Step 1 Find the Key
Based on the rotation rules and the piece of decrypted message:
Atvt hrqgse, Cnikg
Your friend, Alice
We get the code
251220825122082
1st character 'Y' + 2 is beyond 'Z'. So start back at 'A'.
2nd character 'o' + 5 is 't'.
3rd character 'u' + 1 is 'v'
etc.
The code is probably periodic on 2512208, more precisely, on a rotation of 2512208 since we do not know where the start of the key is, since "Your friend, Alice" is not at the opening of the text.
To find out the first digit in the key,
Known the length of key is 7 and number of letters before the signature is N.
So the message is encrypted this way:
7 digit key  7 digit key  …  N % 7 of key
7 letters  7 letters  …  N % 7 letters
The final key period in the message prior to signature is incomplete with (N % 7) digits used.
The remaining part of the key period (7  N % 7) goes to the signature"Your friend, Alice".
So the first complete key period in "Your friend, Alice" starts at position (7  N % 7).
In the test case give, there are 92 letters before the signature Your friend, Alice.
N = 92
(7  N % 7) = 6
Therefore the start of key 2512208 is at the 6th index position which is the 8.
So the actual key is 8251220,
Step 2 Recover from Rotation
Once the key is found, what left is just to rotate the encrypted message back.
Assume current letter in the encrypted message is msg[i] and current key digit is key[j],
original letter = msg[i]  key[j] (if original letter underflows ‘a’/’A’, start again from ‘z’/‘Z’).
public String decrypt(String input, int[] key) {
StringBuilder res = new StringBuilder();
int i = 0;
for(char c: input.toCharArray()) {
if(i == key.length) i = 0;
if(Character.isLetter(c)) {
char firstLetter = c <= 'Z' ? 'A' : 'a';
c = (char)(c  key[i]);
if(c < firstLetter) c = (char)(c + 26);
i++;
}
res.append(c);
}
return res.toString();
}
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Solution to III.
int sqrt(int x) {
if (x == 0)
return x;
int left = 1, right = x;
while (true) {
int mid = (left + right) / 2;
if (mid > x / mid)
right = mid  1;
else if (mid + 1 > x / (mid + 1)) //mid < x / mid
return mid;
else //mid < x / mid
left = mid + 1;
}
}
IV. is on LC
V. Lossy Counting & Sticky Sampling
Solution to Closest K Nodes
vector<int> closestKValues(TreeNode* root, double target, int k) {
vector<int> res;
inorder(root, target, k, res);
return res;
}
void inorder(TreeNode *root, double target, int k, vector<int> &res) {
if (!root) return;
inorder(root>left, target, k, res);
if (res.size() < k) res.push_back(root>val);
else if (abs(root>val  target) < abs(res[0]  target)) {
res.erase(res.begin());
res.push_back(root>val);
} else return;
inorder(root>right, target, k, res);
}
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
@ChrisK
There were two versions of code provided  one for a set with no dupes and the other one for a set with dupes.
It is not counting any cases twice since there is a while loop at the end of dfs() that hops i over any duplicated elements.
I would appreciate it if you read the thing more thoroughly before making assumptions.
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Solution:
How to combine the 4 given card ranks with operators +, , x and / to reach 24.
Backtrack to print all possible combinations.
public void solve(int[] cards) {
boolean[] played = new boolean[4];
for(int i = 0; i < 4; i++) {
StringBuilder str = new StringBuilder(String.valueOf(cards[i]));
played[i] = true;
solve(cards, played, cards[i],str);
played[i] = false;
}
}
private void solve(int[] cards, boolean[] played, double res, StringBuilder str) {
if(played[0] && played[1] && played[2] && played[3]) {
if(res == 24)
System.out.println(str.toString());
return;
}
for(int i = 0; i < 4; i++) {
int len = str.length();
if(!played[i]) {
played[i] = true;
str.insert(0, '(');
str.append("+" + cards[i] + ")");
solve(cards, played, res + cards[i], str);
str.setCharAt(len + 1, '');
solve(cards, played, res  cards[i], str);
str.deleteCharAt(0);
str.deleteCharAt(str.length()  1);
str.setCharAt(len, '*');
solve(cards, played, res * cards[i], str);
str.setCharAt(len, '/');
solve(cards, played, 1.0 * res / cards[i], str);
str.delete(len, str.length());
played[i] = false;
}
}
}

aonecoding
August 14, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Solution:
I. If it is a writeheavy application, create a Fenwick Tree to store for every toggle(i, j), add 1 to node i and 1 to node j (O(logN)). Upon calling isOn(k), get the cumulative sum (O(logN)) till the kth node. If sum is odd, then bulb is on. Otherwise bulb is off.
II. If it is readheavy, create a bit map that toggles in linear time and reads in constant time.
//Fenwick Tree Solution
public class ToggleBulbs {
int[] sum;
public ToggleBulbs(int n) {
sum = new int[n];
}
public boolean isOn(int i)
{
return read(i)%2==1;
}
public void toggle(int start,int end)
{
update(start,1);
update(end+1,1);
}
private int read(int idx){
int ans = 0;
while (idx > 0){
ans += sum[idx];
idx = (idx & idx);
}
return ans;
}
private void update(int idx ,int val){
while (idx <= sum.length){
sum[idx] += val;
idx += (idx & idx);
}
}
}

aonecoding
August 09, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
public void powerOf2Paths(int N) {
List<Integer> path = new ArrayList<>();
path.add(0);
powerOf2PathsHelper(4, 0, path);
}
public void powerOf2PathsHelper(int N, int num, List<Integer> path) {
if(num == N) {
System.out.println(path);
}
for(int i = 0; num + (1 << i) <= N; i++) {
int sum = num + (1 << i);
path.add(sum);
powerOf2PathsHelper(N, sum, path);
path.remove(path.size()  1);
}
}

aonecoding
August 09, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
//get the number of connected components in a list
public int numberOfGroups(Set<Node> nodes) {
Set<Node> visited = new HashSet<>();
int cnt = 0;
for(Node node: nodes) {
while(!visited.contains(node)) {
if(nodes.contains(node)){
visited.add(node);
node = node.next;
} else {
cnt++;
break;
}
}
}
return cnt;
}

aonecoding
August 09, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Solution:
I. If the given arr has unique and distinct elements, it is like the two sum problem then (have two pointers and find out for each j, what's the corresponding i so that arr[i] + arr[j] is just smaller than target K ). The subset count for i to j will be pow(2, j  i).
II. While there are dupes in arr, backtracking is needed to figure out all the subsets possible.
//no dupes
int countSubset(vector<int> & arr, int target) {
int i = arr.size()  1;
while(i >= 0 && arr[i] << 1 >= target) i;
if(i == 1) return 0;
int count = 0, j = i;
while(i >= 0) {
while(j < arr.size()  1 && arr[j + 1] + arr[i] < target) j++;
count += pow(2, j  i);
i;
}
return count;
}
//with dupes
void dfs(vector<int> nums, int idx, int &res, vector<int> &cur, int target)
{
if(idx == nums.size())
{
return;
}
else
{
for(int i = idx; i < nums.size(); i++)
{
cur.push_back(nums);
if((cur.size() == 1 && cur[0] < target)  (cur[0] + cur.back() < target))
{
for(auto it : cur)
{
cout<<it<<" ";
}
cout<<endl;
res++;
dfs(nums, i + 1, res, cur, target);
}
cur.pop_back();
while(i < nums.size()  1 && nums == nums[i + 1])i++;
}
}
}
int countSubset2(vector<int> nums, int target)
{
int res = 0;
vector<int> cur;
dfs(nums, 0, res, cur, target);
return res;
}
int main()
{
vector<int> nums = {2, 2, 3, 5, 7};
cout<<countSubset2(nums, 8)<<endl;
}

aonecoding
August 06, 2017 Hi Fernando,
I interpret the problem this way  making someone my colleague means having him into my team (assigning my manager to him). Since it is a design problem it's openended and your solution would be good as well.
Thanks for the reply!
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Solution:
Breath First Search.
Create a map that stores Map<Node, [PreviousNode, Cost]> the cost to the current node.
Since the question asks for the actual shortest path, in the map also store the previous node in the path.
During the BFS, if the current node has been visited before, but the current cost < former cost, update the cost and route for the current node (only keep the min cost route). Otherwise if current cost > former cost, stop search by not including the current node into the BFS queue.
To stand for a node in the map with an integer rather than a point (x, y), do
nodeID = x * matrix[0].length + y;
To convert the ID back to a point, do
x = nodeID / matrix[0].length;
y = nodeID % matrix[0].length;
//Followup
public void minCostPath(int[][] matrix) {
Queue<Integer> queue = new ArrayDeque<>();
Map<Integer, int[]> map = new HashMap<>(); //key: current location; value[0]: the previous node from where it gets to the current location, value[1]:total cost up to current node
for(int j = 0; j < matrix[0].length; j++) { //put first row into queue
if(matrix[0][j] != 0) {
queue.add(j);
map.put(j, new int[] {1, matrix[0][j]});
}
}
int destination = 1, minCost = Integer.MAX_VALUE;
while(!queue.isEmpty()) {
int id = queue.poll();
int fromX = id / matrix[0].length, fromY = id % matrix[0].length;
if(fromX + 1 < matrix.length) {
int cost = moveMinCost(queue, map, matrix, id, fromX + 1, fromY);
if (cost >= 0 && fromX + 1 == matrix.length  1) {
if (cost < minCost) {
destination = id + matrix[0].length;
minCost = cost;
}
}
}
if(fromY + 1 < matrix[0].length)
moveMinCost(queue, map, matrix, id, fromX, fromY + 1);
if(fromX  1 >= 0)
moveMinCost(queue, map, matrix, id, fromX  1, fromY);
if(fromY  1 >= 0)
moveMinCost(queue, map, matrix, id, fromX, fromY  1);
}
if(destination == 1) return; //no such path from first row to last row
while(map.containsKey(destination)) { //print shortest path from destination to source
int x = destination / matrix[0].length, y = destination % matrix[0].length;
System.out.println("(" + x + ","+ y + "),");
destination = map.get(destination)[0];
}
}
private int moveMinCost(Queue<Integer> queue, Map<Integer, int[]> map, int[][] matrix, int from, int x, int y) {
if(matrix[x][y] == 0) return 1;
int id = x * matrix[0].length + y;
int cost = map.get(from)[1] + matrix[x][y];
if(!map.containsKey(id)  map.get(id)[1] > cost) {
map.put(id, new int[]{from, cost});
queue.add(id);
return cost;
}
return 1;
}

aonecoding
August 03, 2017 class Employee {
int id;
private String name;
//...other personal information
private Employee manager;
private List<Employee> subordinates; //direct subordinates
public Employee(int id, String name) {
this.id = id;
this.name = name;
subordinates = new ArrayList<>();
}
boolean isManager(Employee manager) {
Employee upperLevel = this.manager;
while(upperLevel != null && upperLevel != manager) {
upperLevel = upperLevel.manager;
}
return upperLevel.manager == manager;
}
void beColleague(Employee p) {
p.setManager(this.manager);
}
void setManager(Employee m) {
if(manager != null) { //remove from subordinate's list of current manager
manager.deleteSubordinate(this);
}
manager = m;
m.addSubordinate(this); //add to new manager's subordinate's list
}
private void deleteSubordinate(Employee m) {
subordinates.remove(m);
}
private void addSubordinate(Employee m) {
subordinates.add(m);
}
}
public class Employment {
private Employee admin;
private Map<Integer, Employee> employees; //id: employee
public Employment() {
admin = new Employee(0, "ADMINISTRATOR"); //root of the employment tree, the highest level supervisor
employees = new HashMap<>();
employees.put(0, admin);
}
public void assignManager(int p1, int p2) {
employees.get(p2).setManager(employees.get(p1));
}
public void beColleague(int p1, int p2) {
employees.get(p2).beColleague(employees.get(p1));
}
public boolean isManager(int p1, int p2) {
return employees.get(p2).isManager(employees.get(p1));
}
//public void addEmployee(int p);
//public void deleteEmployee(int p);
}
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Solution to followup: Randomly select a rectangle based on the areas as the weights (larger weights leads to higher probability). Then randomly find a point from the chosen rectangle.
public class RandomSelectFromRectangle {
class Rectangle {
int x1, x2, y1, y2; //top left (x1, y1), bottom right (x2, y2)
}
class Point {
int x, y;
public Point(int a, int b) {
x = a;
y = b;
}
}
final Random rand = new Random();
//Round2
public Point randomSelectFrom(Rectangle rectangle) {
return new Point(rectangle.x1 + rand.nextInt(rectangle.x2  rectangle.x1 + 1),
rectangle.y2 + rand.nextInt(rectangle.y1  rectangle.y2 + 1));
}
//Round2 followup
//first of all decide which rectangle yields the point (randomly select a rectangle based on area as the weight)
//then apply randomSelectFrom(rectangle) on the selected rectangle
public Point randomSelectFrom(Rectangle[] rectangles) {
int selected = 1, total = 0;
for(int i = 0; i < rectangles.length; i++) {
int area = (rectangles[i].x2  rectangles[i].x1) * (rectangles[i].y1  rectangles[i].y2);
if(rand.nextInt(total + area) >= total) {
selected = i;
}
total += area;
}
return randomSelectFrom(rectangles[selected]);
}
}

aonecoding
August 03, 2017 It does not matter. The start time and the end time of intervals are in equal position for this problem.
e.g.
[1, 5], [2, 10], [6, 9] is currently sorted by start. You may merge them from left to right and get the result [1,10].
If they were sorted by end time instead  [1, 5], [6, 9],[2, 10]. You could merge them from right to left and get the same result [1, 10].
It just depends on if you wanna start the merge from the left or right side of the given inteval list.
A sample code for when intervals sorted by start time
public List<Interval> merge(List<Interval> intervals) {
if (intervals.size() <= 1)
return intervals;
// Sort by ascending starting point
intervals.sort((i1, i2) > Integer.compare(i1.start, i2.start));
List<Interval> result = new LinkedList<Interval>();
int start = intervals.get(0).start;
int end = intervals.get(0).end;
for (Interval interval : intervals) {
if (interval.start <= end) // Overlapping intervals, move the end if needed
end = Math.max(end, interval.end);
else { // Disjoint intervals, add the previous one and reset bounds
result.add(new Interval(start, end));
start = interval.start;
end = interval.end;
}
}
// Add the last interval
result.add(new Interval(start, end));
return result;
}
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
//Sol1: O(n) time, O(1) extra memory solution, suitable if the function is rarely called on the data set
public int random(int n, Set<Integer> ex) {
int idx = new Random().nextInt(n  ex.size());
for(int num = 0; num < n; num++) {
if(!ex.contains(num)) {
idx;
}
if(idx == 1) {
return num;
}
}
return 1; //no number is available for selection (n is 0 or every number in range is excluded
}
//Sol2: O(n) extra memory and O(n) time at initialization
//create a list of numbers in [0,n) excluding the numbers in excluded set
//O(1) time on successive calls on the same data set
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
I. At first find found all primes <= N (sieve of Eratosthenes). Getting the sum will be easy then.
Followup:
Cache the sums for any given N to save time. {N:SUM}
Optimization: Don't have to store sums for every N.
When N = 7, N = 8, N = 9, N = 10, the prime sum remains 17.
For N between 11 to 12, the prime sum is 28.
For N between 13 to 16, the sum is 41.
Use a BST structure as the cache. For N = 16, cache:
{2:3, 4:6, 6:11, 10:17, 12:28, 16:41}
For a given N, call cache.ceilingKey(N) to find the bucket for N.
N/log(n) * log(N)
Complexity
Time:
sieve of Eratosthenes takes O(NloglogN) time.
Insert an element into BST takes O(logN), there are N/logN primes in total to be added.
So building the cache takes logN * N / LogN = O(N) time
requesting primeSum(N) takes O(logN)
Space:
sieve of Eratosthenes takes O(N) extra space which will later be release after the cache is created.
Cache: O(N/logN)
import java.util.TreeMap;
public class PrimeSum {
TreeMap<Integer, Integer> sums;
public PrimeSum(int n) { //input the upper limit for all Ns
sums = new TreeMap<>();
// init an array to track prime numbers
boolean[] primes = new boolean[n + 1];
for (int i = 2; i < n; i++)
primes[i] = true;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (primes[i]) {
for (int j = i + i; j < n; j += i)
primes[j] = false;
}
}
// insert sums into cache
int sum = 0;
for(int i = 2; i <= n; i++) {
if(primes[i]) {
sums.put(i  1, sum);
sum += i;
}
}
if(primes[n]) {
sums.put(n, sum);
}
}
public int primeSum(int N) {
Integer ceiling = sums.ceilingKey(N);
//if(ceiling == null) {
//Exception("input value overflows");
//}
return sums.get(ceiling);
}
}

aonecoding
July 28, 2017 public class MultiplicationQueries {
int[] array;
int[] zeroToLeft;
int[] product;
public MultiplicationQueries(int[] a) {
array = a;
if(array.length > 0) {
zeroToLeft = new int[array.length];
product = new int[array.length];
zeroToLeft[0] = array[0] == 0 ? 0: 1;
product[0] = array[0] == 0 ? 0: array[0];
}
for(int i = 1; i < array.length; i++) {
zeroToLeft[i] = array[i] == 0 ? i: zeroToLeft[i  1];
product[i] = array[i] == 0 ? 0: array[i  1] == 0 ? array[i]: array[i] * product[i  1];
}
}
public int query(int i, int j) {
if(i > j  i >= array.length  j >= array.length  i < 0  j < 0) return 1;
if(i == j) return array[i];
return zeroToLeft[j] >= i ? 0: (i == 0  array[i  1] == 0) ? product[j]: product[j] / product[i  1];
}
}

aonecoding
July 25, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Solution
Since query(i, j) gets frequently called, it should run as fast as possible, ideally in O(1) time.
I. When there is 0 between i and j, the query returns 0.
To quickly find out 0 between i and j, initial another array to keep track of at the current index i, where is the closest 0 to the left of i (including i).
II. To get the product of any given range without zero in between, build an array of cumulative products from the first positive number in the nonzero part up to current idx i. So that if there is no zero in between, query(i, j) equals to product[j] / product[i  1] (O(1) time).
e.g. For A = [2, 2, 3, 4, 0, 4, 5, 6]
product array P = [2, 4, 12, 48 ,0, 4, 20 ,120]
query(1, 3) = P[3] / P[1  1] = 48 / 2 = 24
Remember to discuss with the interviewer if the product can get integer overflow
Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Any routing algorithm will solve this problem, such as BFS Dijrsktra's etc.
It's still a challenging problem under the time limit in an interview since it involves first parsing the input string into a graph structure and then run the routing algorithm.
public int minCost(String flights, String from, String to, int k) {
if(from == to) return 0;
if(flights.isEmpty()) return 1;
int[][] edges = parseString(flights,from, to);
Map<Integer, Integer> minCostSet = new HashMap<>();
minCostSet.put(0, 0);
Queue<Integer> prev = new ArrayDeque<>(); //previous level of nodes
prev.add(0);
while(k >= 0 && !prev.isEmpty()) { //BFS
Queue<Integer> current = new ArrayDeque<>();
for(int source: prev) {
for(int destination = 0; destination < edges.length; destination++) {
if(edges[source][destination] > 0) {
int minCost = minCostSet.containsKey(destination) ? minCostSet.get(destination) : Integer.MAX_VALUE;
int newCost = Math.min(minCost, minCostSet.get(source) + edges[source][destination]);
if (minCost > newCost) {
minCostSet.put(destination, newCost);
current.add(destination);
}
}
}
}
prev = current;
k;
}
return minCostSet.containsKey(edges.length  1) ? minCostSet.get(edges.length  1): 1;
}
private int[][] parseString(String flights, String start, String end) {
Map<String, Integer> map = new HashMap<>();
List<int[]> edges = new ArrayList<>();
String[] f = flights.split(",");
map.put(start, 0);
map.put(end, 1);
for(int i = 0; i < f.length; i+=2) {
int idx = f[i].indexOf('');
String src = f[i].substring(0, idx);
String des = f[i].substring(idx + 2);
if(!map.containsKey(src)) {
map.put(src, map.size()  1);
}
if(!map.containsKey(des)){
map.put(des, map.size()  1);
}
if(map.get(src) != 1) { //exclude flights that departs from the ultimate destination
edges.add(new int[]{map.get(src), map.get(des), Integer.parseInt(f[i + 1])});
}
}
int n = map.size();
int[][] graph = new int[n][n];
for(int[] edge: edges) {
if(edge[1] == 1) edge[1] = n  1;
graph[edge[0]][edge[1]] = edge[2];
}
return graph;
}

aonecoding
July 25, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Solution to Round 4
//input a 4X13 matrix with 4 suits and 13 ranks of cards. set cards[suit][rank] to 1 if this card in hand.
public static boolean handClear(int[][] cards, int hand) {
if(hand == 0) return true;
for(int rank = 12; rank >= 0; rank) {
for(int suit = 0; suit < 4; suit++) {
if(cards[suit][rank] == 1) { //if cards[suit][rank] in hand
cards[suit][rank] = 0; hand;
int smallerRank = rank == 0 ? 12: rank  1; // look for straight flush that end with this card
// watch for Ace as a special case that ***QKA and A23*** both valid
if(cards[suit][smallerRank] == 1) {
cards[suit][smallerRank] = 0; hand;
int r = smallerRank  1;
for(; r >= 0 && cards[suit][r] == 1; r) { //try playing the straight flush found
cards[suit][r] = 0; hand;
if(handClear(cards, hand)) return true;
}
r++;
for(; r <= smallerRank; r++) { //backtrack if play did not work
cards[suit][r] = 1; hand++;
}
}
//look for 3/4 of a kind for cards[suit][rand]
int n = cards[0][rank] + cards[1][rank] + cards[2][rank] + cards[3][rank];
if(n == 3  n == 2) {
int tmp1 = cards[(suit + 1) % 4][rank],
tmp2 = cards[(suit + 2) % 4][rank],
tmp3 = cards[(suit + 3) % 4][rank];
cards[(suit + 1) % 4][rank] = 0; //try playing the 3/4 of a kind
cards[(suit + 2) % 4][rank] = 0;
cards[(suit + 3) % 4][rank] = 0;
hand = n;
if(handClear(cards, hand)) return true;
cards[(suit + 1) % 4][rank] = tmp1; //backtrack if play did not work
cards[(suit + 2) % 4][rank] = tmp2;
cards[(suit + 3) % 4][rank] = tmp3;
hand += n;
}
cards[suit][rank] = 1; hand++;
}
}
}
return false;
}

aonecoding
July 23, 2017 Looking for interview experience sharing and mentor?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Code),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Solution
For the first problem a hash set of {IPs} may simply solve it.
However in the followups as the amount of data cumulates, if the IPs are stored as strings, 4GB is becomes absolutely insufficient, since there are over 4 billion IPs out there and each ip as a string takes at least 9 bytes.
Even if convert ip to integer(8B), it wouldn't be enough.
An approach is to go with bit set. Then each ip takes only 1 bit. Have a bit set to store whether an ip occurs and another set to store whether an ip repeats.
This takes 2 * 2^32 bit = ~1GB > fits in RAM.
public class IPFilter {
long[] map; //mark all ip that showed up
long[] repeatedIP; //mark all ips that repeatedly showed up
public IPFilter() {
//there's 2^32 IP in total.
// each long integer is identifies 64 IPs.
// Need 2^32 / 2^6 long integers in the bit map
int size = 1 << (32  6);
map = new long[size];
repeatedIP = new long[size];
}
public void addToMap(List<String> IPs) {
for(String ip: IPs) {
long decimal = IPToLong(ip);
int idx = (int)(decimal / 64);
int res = (int)(decimal % 64);
if((map[idx] >> res) == 1) { //repeated ip
repeatedIP[idx] = (1 << res);
} else { //first occurred ip
map[idx] = (1 << res);
}
}
}
private long IPToLong(String ipAddress) { //convert ip (base 256) to decimal
String[] ipAddressInArray = ipAddress.split("\\.");
long result = 0;
for (int i = 0; i < ipAddressInArray.length; i++) {
int power = 3  i;
int ip = Integer.parseInt(ipAddressInArray[i]);
result += ip * Math.pow(256, power);
}
return result;
}
}

aonecoding
July 23, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Solution to 2/5: The number of minutes in a day is constant. Create an array of size 60*24 minutes in a day. Mark true on meeting schedules.
public boolean meetingOverlap(int[][] meetings) {
boolean[] schedule = new boolean[24 * 60];
for(int[] time:meetings) {
for(int i = time[0]; i <= time[1]; i++) {
if(schedule[i]) return true;
schedule[i] = true;
}
}
return false;
}

aonecoding
July 20, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
4/5 is a graph problem  similar to finding the number of connected components in graph.
DFS solution:
In this graph every node has at most 2 edges. Every position (x, y) has 2 nodes. If it's a '/' in (x, y) and current node is upper half of (x,y), the next two nodes to search is right half of (x  1, y) and lower half of (x, y  1).
Other than DFS, union find and BFS will work as well.
public int segmentCount(char[][] m) {
int len = m[0].length;
boolean[] upperHalf = new boolean[m.length * len];
boolean[] lowerHalf = new boolean[m.length * len];
int count = 0;
for(int i = 0; i < m.length; i++) {
for(int j = 0; j < len; j++) {
if(!upperHalf[i*len + j]) {
count++;
dfs(m, upperHalf, lowerHalf, i, j, 0);
}
if(!lowerHalf[i*len + j]) {
count++;
dfs(m, upperHalf, lowerHalf, i, j, 1);
}
}
}
return count;
}
//upper:0, lower:1, left:2, right:3
private void dfs(char[][] m, boolean[] upperHalf, boolean[] lowerHalf, int x, int y, int position) {
if(x < 0  x == m.length  y == m[0].length  y < 0) {
return;
}
if((position == 2 && m[x][y] == '\\')  (position == 3 && m[x][y] == '/')) position = 1;
if((position == 2 && m[x][y] == '/')  position == 3 && m[x][y] == '\\') position = 0;
int id = x * m[0].length + y;
if((position == 0 && upperHalf[id])  (position == 1 && lowerHalf[id])) { //if visited
return;
}
if(position == 0) upperHalf[id] = true;
else lowerHalf[id] = true;
if(position == 0 && m[x][y] == '\\') {
dfs(m, upperHalf, lowerHalf, x, y + 1, 2); //go right
dfs(m, upperHalf, lowerHalf, x  1, y, 1); //go up
}
if(position == 0 && m[x][y] == '/') {
dfs(m, upperHalf, lowerHalf, x, y  1, 3); //go left
dfs(m, upperHalf, lowerHalf, x  1, y, 1); //go up
}
if(position == 1 && m[x][y] == '\\') {
dfs(m, upperHalf, lowerHalf, x, y  1, 3); //go left
dfs(m, upperHalf, lowerHalf, x + 1, y, 0); //go down
}
if(position == 1 && m[x][y] == '/') {
dfs(m, upperHalf, lowerHalf, x, y + 1, 2); //go right
dfs(m, upperHalf, lowerHalf, x + 1, y, 0); //go down
}
}

aonecoding
July 20, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates targeting FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
public boolean match(String str, String pattern) {
int occurLower = 0, occurUpper = 0;
char prev = '\0';
int i = 0, j = 0;
while(j < pattern.length()) {
char c = i == str.length() ? '\0': str.charAt(i);
if (occurUpper == 0  prev == pattern.charAt(j)  (c != prev && occurLower <= 0)) {
String range = j + 1 < pattern.length() && pattern.charAt(j + 1) == '{' ?
pattern.substring(j + 2, pattern.indexOf('}', j + 2)): "";
int[] r = getRange(range);
occurLower = prev == pattern.charAt(j) ? occurLower + r[0] : r[0];
occurUpper = prev == pattern.charAt(j) ? occurUpper + r[1] : r[1];
prev = pattern.charAt(j);
j = range.isEmpty() ? j + 1: pattern.indexOf('}', j + 2) + 1;
}
if (c == prev) {
occurLower;
occurUpper;
i++;
} else if (occurLower > 0) {
return false;
}
}
while(i < str.length()) {
if(str.charAt(i) != prev  occurUpper == 0) return false;
else {
occurUpper;
i++;
}
}
return true;
}
private int[] getRange(String b) {
if(b.isEmpty()) return new int[]{1,1};
int comma = b.indexOf(',');
return new int[]{
Integer.parseInt(b.substring(0, comma)),
Integer.parseInt(b.substring(comma + 1))  1
};
}

aonecoding
July 17, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
ONE TO ONE realtime coaching offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
solution 4.1
public TreeNode solve(TreeNode root) {
TreeNode[] res = treetoDLL(root);
if(res == null) return null;
res[0].left = res[1]; //make linked list circular
res[1].right = res[0];
return res[0]; //return a node in the chain
}
public TreeNode[] treetoDLL(TreeNode root) { //recursion to create linked list in place
if(root == null) return null;
TreeNode[] prev = treetoDLL(root.left);
TreeNode[] next = treetoDLL(root.right);
TreeNode[] res = new TreeNode[] {root, root};
if(prev != null) {
prev[1].right = root;
root.left = prev[1];
res[0] = prev[0];
}
if(next != null) {
next[0].left = root;
root.right = next[0];
res[1] = next[1];
}
return res;
}

aonecoding
July 15, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
ONE TO ONE realtime coaching offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
public static int divide(int dividend, int divisor) {
//if(divisor == 0) throw new Exception();
int sign = 1;
//figure out the sign of the result
if((dividend < 0 && divisor > 0)
 (dividend > 0 && divisor < 0)) {
sign = 1;
}
if(dividend < 0) dividend = dividend;
if(divisor < 0) divisor = divisor;
int n = 1; //get the range of result [n, 2n], where n is doubled every round
while(dividend > (n << 1) * divisor) {
n <<= 1;
}
//now it's known that the result is between [n, 2n]
//so in the dividend has a sum of more than n and less than 2n divisors in total
//to figure out exactly how many divisors sum up to the dividend,
// break down the problem to result = n + divide(dividend  n * divisor, divisor)
// next round the dividend becomes (dividend  n * divisor) with n added to the result.
// proceed to figure out the range [x, 2x] of result for the new dividend, where x can be n/2, n/4, n/8...
// whenever the x is found, add x to the result and deduce x * divisor from the dividend
// util n is 0 or dividend is 0
//If written in math, the formula looks like dividend = ([T/F]* n + [T/F]* n/2 + [T/F]* n/ 4 + [T/F]* n/ 8...) * divisor
//The quotient will be ([T/F]* n + [T/F]* n/2 + [T/F]* n/ 4 + [T/F]* n/ 8...), [T/F] depends on (dividend  n * divisor) >= 0
int result = 0;
while(n > 0 && dividend > 0) {
if(dividend  n * divisor >= 0) {
dividend = n * divisor;
result += n;
}
n >>= 1;
}
return result * sign;
}

aonecoding
July 15, 2017 Looking for interview experience sharing and coaching?
Visit aonecode.com for private lessons by FB, Google and Uber engineers
ONE TO ONE realtime coaching offers
SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Candidate's solution to 1.1
int diameterOfBinaryTree(TreeNode* root) {
maxDown(root);
return maxLen;
}
int maxDown(TreeNode* r) {
if (!r) return 0;
int maxL = maxDown(r>left), maxR = maxDown(r>right);
maxLen = max(maxLen, maxL+maxR);
return max(maxL, maxR) + 1;
}
int maxLen = 0;
Solution to 1.2
public static List<int[]> maxOverlap(int[][] intervals) { //input [[start1, end1], [start2, end2]...]
int[] starts = new int[intervals.length];
int[] ends = new int[intervals.length];
for(int i=0; i<intervals.length; i++) {
starts[i] = intervals[i][0];
ends[i] = intervals[i][1];
}
Arrays.sort(starts);
Arrays.sort(ends);
int rooms = 0;
int endsItr = 0;
int mark = 1;
for(int i=0; i<starts.length; i++) {
if (starts[i] < ends[endsItr]) {
rooms++;
mark = endsItr; //mark where the first max overlap zone appears
} else {
endsItr++;
}
}
List<int[]> points = new ArrayList<>(); //result
while(mark <= ends.length  rooms) {
if(ends[mark] > starts[mark + rooms  1]) {
points.add(new int[]{starts[mark + rooms  1], ends[mark]});
}
mark++;
}
//optional: convert nonoverlap intervals in 'points' to collection of numbers if necessary
return points;
}

aonecoding
July 15, 2017 Solution to 1st Question in Round2 blog.csdn.net/taoqick/article/details/21814849
 aonecoding July 11, 2017Looking for interview experience sharing and coaching?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Solution: Dynamic programming with a map of a map.
public static int llac(int[] array) {
if(array.length == 0) return 0;
int max = 1;
Map<Integer,Map<Integer, Integer>> index_to_llac = new HashMap<>(); //Map<currentIndex, Map<difference, length>>
for(int current = 1; current < array.length; current++) {
index_to_llac.put(current, new HashMap<>());
for(int prev = 0; prev < current; prev++) {
int diff = array[current]  array[prev];
int length = 2;
if(index_to_llac.containsKey(prev) && index_to_llac.get(prev).containsKey(diff)) {
length = index_to_llac.get(prev).get(diff) + 1;
}
Map<Integer, Integer> diff_to_llac = index_to_llac.get(current);
//if this is a arithmetic progression with [diff] exists before current, add 1 to the length to include current in the progression
//otherwise, [prev, current] forms a progression of size 2
diff_to_llac.put(diff, length);
max = Math.max(length, max);
}
}
return max;
}

aonecoding
July 05, 2017 Looking for interview experience sharing and coaching?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Looking for interview experience sharing and coaching?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Simulating rain
Break down the 1 meter walkway to 100 centimeters. Originally the whole centimeter is dry
so left = 0, right=0.01(meter); When the rain drop falls between on centimeter i (covers 0.4 centimeters of i)and centimeter i+1( 0.6 centimeters of i + 1), push the right boundary of centimeter[i] to the left by centimeter[i].right  0.004. Same thing push the left boundary of centimeter[i] + 1 to 0.006.
Whenever a centimeter gets to left >= right, increment the fully wet centimeter count (wetCnt) by 1. When wetCnt hits 100, the whole meter is covered in rain.
public class RainDrop {
static class Interval {
double left = 0, right = 0.01;
boolean isWet() {
return left >= right;
}
}
public static void main(String[] args) {
simulateRainDrop();
}
public static void simulateRainDrop() {
Interval[] sidewalk = new Interval[100];
for (int i = 0; i < 100; i++) {
sidewalk[i] = new Interval();
}
int cnt = 0, wetCnt = 0;
while (wetCnt < 100) {
++cnt;
double p = Math.random();
double left = p  0.005;
double right = p + 0.005;
if (left >= 0) {
int idx = (int) (left / 0.01);
if (!sidewalk[idx].isWet()) {
double iright = left  idx * 0.01; //update seg[i].right with left bound of rain
if (iright < sidewalk[idx].right) {
sidewalk[idx].right = iright;
if (sidewalk[idx].isWet())
++wetCnt;
}
}
}
if (right <= 1) {
int idx = (int) (right / 0.01);
if (!sidewalk[idx].isWet()) {
double ileft = right  idx * 0.01;//update seg[i + 1].left with right bound of rain
if (ileft > sidewalk[idx].left) {
sidewalk[idx].left = ileft;
if (sidewalk[idx].isWet())
++wetCnt;
}
}
}
}
System.out.println(cnt);
}
}

aonecoding
June 22, 2017 Looking for interview experience sharing and coaching?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Solution:
append and get are naturally done in constant time with ArrayList. To achieve add_to_all in constant time, have an extra variable 'addition' to store the added number. For any incoming number x to append, append(x  addition) instead. The get() method returns get(index) + addition.
Followup:
We could do the same thing for the multiply to all. keep track of the current multiplication factor and append the new number x by append(x / factor). However this brings the data type into double which is lousy.
A way around that is have another array divisor to keep track of the current factor when a new number x is appended at index i. Append x as it is. But later when x is requested, return x * factor / divisor.get(i).
Don't forget that every time the factor changes  such as when it doubles, the addition will be doubled as well.
import java.util.List;
import java.util.ArrayList;
public class Collection {
List<Integer> collection = new ArrayList<>();
List<Integer> divisors = new ArrayList<>();
int factor = 1;
int addition = 0;
public void append(int x) {
collection.add(x  addition);
divisors.add(factor);
}
public int get(int index) {
if(index >= collection.size()) throw new RuntimeException();
return collection.get(index) * (factor / divisors.get(index)) + addition;
}
public void add_to_all(int x) {
addition += x;
}
public void multiply_to_all(int x) {
addition *= x;
factor *= x;
}
}

aonecoding
June 15, 2017 Looking for interview experience sharing and coaching?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
public class CircularBuffer<T> {
private T[] buffer;
private int tail;
private int head;
@SuppressWarnings("unchecked")
public CircularBuffer(int n) {
buffer = (T[]) new Object[n];
tail = 0;
head = 0;
}
public void add(T toAdd) {
if (head != (tail  1)) {
buffer[head++] = toAdd;
} else {
//throw new BufferOverflowException();
}
head = head % buffer.length;
}
public T get() {
T t = null;
int adjTail = tail > head ? tail  buffer.length : tail;
if (adjTail < head) {
t = (T) buffer[tail++];
tail = tail % buffer.length;
} else {
//throw new BufferUnderflowException();
}
return t;
}
public String toString() {
return "CircularBuffer(size=" + buffer.length + ", head=" + head + ", tail=" + tail + ")";
}
}

aonecoding
June 06, 2017 Looking for interview experience sharing and coaching?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
public static int divide(int dividend, int divisor) {
if(divisor == 0) throw new RuntimeException();
int sign = 1;
//figure out the sign of the result
if((dividend < 0 && divisor > 0)
 (dividend > 0 && divisor < 0)) {
sign = 1;
}
if(dividend < 0) dividend = dividend;
if(divisor < 0) divisor = divisor;
int n = 1; //get the range of result [n, 2n], where n is doubled every round
while(dividend > (n << 1) * divisor) {
n <<= 1;
}
//now it's known that the result is between [n, 2n]
//so in the dividend has a sum of more than n and less than 2n divisors in total
//to figure out exactly how many divisors sum up to the dividend,
// break down the problem to result = n + divide(dividend  n * divisor, divisor)
// next round the dividend becomes (dividend  n * divisor) with n added to the result.
// proceed to figure out the range [x, 2x] of result for the new dividend, where x can be n/2, n/4, n/8...
// whenever the x is found, add x to the result and deduce x * divisor from the dividend
// util n is 0 or dividend is 0
//If written in math, the formula looks like dividend = ([T/F]* n + [T/F]* n/2 + [T/F]* n/ 4 + [T/F]* n/ 8...) * divisor
//The quotient will be ([T/F]* n + [T/F]* n/2 + [T/F]* n/ 4 + [T/F]* n/ 8...), [T/F] depends on (dividend  n * divisor) >= 0
int result = 0;
while(n > 0 && dividend > 0) {
if(dividend  n * divisor >= 0) {
dividend = n * divisor;
result += n;
}
n >>= 1;
}
return result * sign;
}

aonecoding
June 06, 2017 Looking for interview experience sharing and coaching?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
Having come across a nested list node N. Recursively flatten the node into a plain list. Return the Head and Tail of the flattened list. Make the node before N point to Head. Make Tail.next point to N.next.
public class FlattenLinkedList {
public static Wrapper flatten(ListNode head) {
if(head == null) return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode node = dummy;
while(node.next != null) {
if(node.next.data != null) {
node = node.next;
} else {
Wrapper flattened = flatten(node.next.list);
if(flattened.tail != null) {
flattened.tail.next = node.next.next; //delete the node with nested list
node.next = flattened.head;
node = flattened.tail;
} else {
node.next = node.next.next;
}
}
}
return new Wrapper(dummy.next, node);
}
}
class ListNode<T> {
ListNode next;
T data; //when data is not null, this node carries actual data
ListNode list; //when data is null, this node carries a nested list
public ListNode(T data) {
this.data = data;
}
public ListNode() {
}
//.....other constructors
}
class Wrapper {
ListNode head;
ListNode tail;
public Wrapper(ListNode h, ListNode t) {
head = h;
tail = t;
}

aonecoding
June 06, 2017 Looking for interview experience sharing and mentors?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber, our ONE TO ONE courses cover everything in an interview including latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us aonecoding@gmail.com with any questions. Thanks for reading.
Solution:
The problem is about scanning a graph. So either DFS or BFS will work.
Perceive the room as a 2D grid and the robot initializes at (0, 0).
The thing special about this problem is that the shape of the room is unknown. Therefore it is harder for us to mark the visited places. The normal approach like using a boolean matrix wouldn't work here.
Instead we can go with a map of a set Map<Integer, Set<Integer>>. For any (X, Y) location that exists, store it in the map Map<x, Set<all the Ys in line X>>.
Then backtracking solves the problem. Don't forget to move the robot back to where it was from after each layer of recursion. So it is necessary to have an argument that keeps track of from where the robot comes to the current point.
public class Room {
Robot robot;
//......
//x, y is the current location of the robot
//from is the last step taken
//map<x, set<y>> marks the places visited
public int getArea(int x, int y, int from, Map<Integer, Set<Integer>> room) {
if(room.containsKey(x) && room.get(x).contains(y)) { //if this place was visited
robot.move(moveBack(from)); //turn robot back
return 0; //add 0 to total area
}
//mark current place visited
if(!room.containsKey(x)) room.put(x, new HashSet<>());
room.get(x).add(y);
int area = 1;
if(from != 0 && robot.move(moveBack(0))) {//if robot was not moved to current place from below, move robot down
area += getArea(x, y  1, 0, room);
}
if(from != 1 && robot.move(moveBack(1))) {//if robot didn't come from the right, move it to the right
area += getArea(x + 1, y, 1, room);
}
if(from != 2 && robot.move(moveBack(2))) { //if robot didn't come from above, move it up
area += getArea(x, y + 1, 2, room);
}
if(from != 3 && robot.move(moveBack(3))) { //if robot didn't come from the left, move it to the left
area += getArea(x  1, y, 2, room);
}
//after counting the areas around the current location, walk robot back to where it was from
robot.move(moveBack(from));
return area;
}
private int moveBack(int from) {
if(from == 0) return 2;
if(from == 1) return 3;
if(from == 2) return 0;
return 1;
}
}

aonecoding
May 27, 2017 Looking for interview experience sharing and mentors?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy, String and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after weeks of training.
Welcome to email us aonecoding@gmail.com with any questions. Thanks for reading.
Solution by the interviewee:
public int findBlockCount(List<Node> pointers, Node head)
{
HashMap<Node, Integer> map = new HashMap();
for(Node n:pointers)
{
map.put(n, 1);
}
int block = 0;
boolean newblock = true;
Node itr = head;
while(itr!=null)
{
if(map.containsKey(itr))
{
if(newblock)
{
block++;
newblock = false;
}
}else
{
newblock = true;
}
itr = itr>next;
}
return block;
}

aonecoding
May 27, 2017 Looking for interview experience sharing and mentors?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us aonecoding@gmail.com with any questions. Thanks for reading.
Backtracking for all the combinations to solve this problem.
public class StringToSingleChar {
public static void main(String[] args) {
StringToSingleChar t = new StringToSingleChar("ABACABB");
System.out.println(t.pathLen());
}
List<Character> str;
public StringToSingleChar(String s) {
str = new ArrayList<>();
for(char c: s.toCharArray()) {
str.add(c);
}
}
public int pathLen() {
if(str.size() == 0) return 1;
if(str.size() == 1) return 0;
if(invalidToConvert()) return 1;
for(int i = 0; i < str.size()  1; i++) {
char curr = str.get(i), next = str.get(i + 1);
if(curr != next) {
//backtracking, try to convert any two adjacent chars in str
str.set(i, convert(curr, next));
str.remove(i + 1);
int steps = pathLen();
if(steps >= 0) return steps + 1;
//recover the str after the recursive calls
str.set(i, curr);
str.add(i + 1, next);
}
}
return 1;
}
//check if given string is invalid like "AAAAA..." or "BBBBB..." or "CCCCC..."
private boolean invalidToConvert() {
for(int i = 0; i < str.size()  1; i++) {
if(str.get(i) != str.get(i + 1)) return false;
}
return true;
}
private char convert(char a, char b) {
if(a != 'C' && b != 'C') return 'C';
if(a != 'B' && b != 'B') return 'B';
return 'A';
}
}

aonecoding
May 10, 2017 Not a typical coding interview question but I like it. When problem solving goes too far we'd like to get back to the real world.
Looking for interview experience sharing and mentors?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us aonecoding@gmail.com with any questions. Thanks for reading.
class Photo implements Comparable<Photo> {
String location;
String type;
int year;
int month;
int day;
int hour;
int minute;
int second;
int index; //Convert the given string to a list (one photo as an element). This is the index of the current photo
public Photo(String loc, String t, int y, int m, int d, int h, int mm, int s) {
location = loc;
type = t;
year = y;
month = m;
day = d;
hour = h;
minute = mm;
second =s;
}
public int compareTo(Photo o) {
if(year != o.year) return year  o.year;
if(month != o.month) return month  o.month;
if(day != o.day) return day  o.day;
if(hour != o.hour) return hour  o.hour;
if(minute != o.minute) return minute  o.minute;
return second  o.second;
}
}
public class RenamePhotos {
public String solution(String photos) {
if(photos.isEmpty()) return "";
String[] list = photos.split("\n");
//key: location, value: a list of photos taken at the location
Map<String, List<Photo>> map = new HashMap<>();
for(int i = 0; i < list.length; i++) {
Photo photo = createPhoto(list[i]);
photo.index = i;
if(!map.containsKey(photo.location)) {
map.put(photo.location, new ArrayList<>());
}
map.get(photo.location).add(photo);
}
for(String loc: map.keySet()){
List<Photo> photo_by_datetime = map.get(loc);
Collections.sort(photo_by_datetime);
int size = photo_by_datetime.size();
for(int i = 0; i < size; i++) {
//create new name for current photo
StringBuilder str = new StringBuilder();
str.append(photo_by_datetime.get(i).location);
str.append(padZeros(i, size));
str.append('.');
str.append(photo_by_datetime.get(i).type);
//update list with the new name of this photo
list[photo_by_datetime.get(i).index] = str.toString();
}
}
StringBuilder ret = new StringBuilder();
for(String str: list) { //merge new names into a string
ret.append(str);
ret.append('\n');
}
return ret.substring(ret.length()  1);
}
private String padZeros(int i, int len) {
StringBuilder number = new StringBuilder();
number.append(i);
i = number.length();
while(i < len) {
number.insert(0, '0');
i++;
}
return number.toString();
}
//create an instance of photo for each photo name given
private Photo createPhoto(String photo) {
int i = 0;
String type = photo.substring(photo.indexOf('.') + 1, i = photo.indexOf(','));
String location = photo. substring(i + 1, i = photo.indexOf(i + 1, ','));
int year = Integer.parseInt(photo.substring(i + 1, i = photo.indexOf(i + 1, '')));
int month = Integer.parseInt(photo.substring(i + 1, i = photo.indexOf(i + 1, '')));
int day = Integer.parseInt(photo.substring(i + 1, i = photo.indexOf(i + 1, ' ')));
int hour = Integer.parseInt(photo.substring(i + 1, i = photo.indexOf(i + 1, ':')));
int minute = Integer.parseInt(photo.substring(i + 1, i = photo.indexOf(i + 1, ':')));
int second = Integer.parseInt(photo.substring(i + 1));
return new Photo(location, type, year, month, day, hour, minute, second);
}
}

aonecoding
May 05, 2017 def pow(x, n):
if n == 0:
return 1
neg = False
if n < 0:
neg = True
n = n
pow = 1
while n > 1:
if n % 2 == 1:
pow *= x
n /= 2 # x^n = (x ^ 2) ^ (n / 2)
x *= x
return 1/(pow * x ) if neg else pow * x
Looking for interview experience sharing and mentors?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us aonecoding@gmail.com with any questions. Thanks for reading.
public int largestProduct3(int[] array) {
Arrays.sort(array);
int n = array.length;
int maxProduct;
//case> pick the last 3 numbers(when the array has only negative, or only positive numbers)
maxProduct = array[n  1] * array[n  2] * array[n  3];
//case> pick 2 numbers from the left end and 1 number from the right end
maxProduct = Math.max(maxProduct, array[0] * array[1] * array[n  1]);
return maxProduct;
}
Looking for interview experience sharing and mentors?
Visit A++ Coding Bootcamp at aonecode.com.
Given by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us aonecoding@gmail.com with any questions. Thanks for reading.
Looking for interview experience sharing and mentors?
Visit A++ Coding Bootcamp at aonecode.com.
Taught by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us aonecoding@gmail.com with any questions. Thanks!
public boolean validForSharing(List<SharedParagraph> sharedParagraphs, Book book) {
if(sharedParagraphs.isEmpty()) return true;
//sort sharedParagraphs
Collections.sort(sharedParagraphs, new Comparator<SharedParagraph>(){
public int compare(SharedParagraph i1, SharedParagraph i2){
if(i1.start!=i2.start)
return i1.starti2.start;
else
return i1.endi2.end;
}
});
SharedParagraph pre = sharedParagraphs.get(0);
int totalShared = 0, start = 0, end = 0;
for(int i=0; i<sharedParagraph.size(); i++){
SharedParagraph curr = sharedParagraphs.get(i);
if(curr.start >= end) {
totalShared += end  start;
start = curr.start;
end = curr.end;
} else {
end = Math.max(curr.end, end);
}
}
totalShared += end  start;
return result <= book.size() / 10;
}

aonecoding
April 23, 2017 The solution takes O( L * log(S)) time and O(log(S)) space, where L is the average length of the urls, S is the size of the url list. Because it was said to be a long list, we trade space for time.
Otherwise if space if more valuable, just compare every character at the same index over the whole url list, which takes O(SL) time in the worst case.
//return the last index of the common prefix of url. To get the common prefix, just call url.substring(last index + 1).
public int longestCommonPrefix(String[] urls) {
//the length of a url will not exceed the limit of max integer
return longestCommonPrefix(urls, 0, urls.length()  1, Integer.MAX_VALUE);
}
//recursive divide and conquer approach. To save time every round deal with half of the remaining url list since the list is assumed to be long
private int longestCommonPrefix(String[] urls, int start, int end) {
if(end < start) return 0;
if(end == start) return urls[start].length()  1;
int prefix1 = urls[start].length()  1, prefix2 = urls[end].length()  1;
if(start < end  1) {
int mid = (start + end) / 2;
prefix1 = longestCommonPrefix(urls, start, mid);
prefix2 = longesetCommonPrefix(urls, mid + 1, end);
}
for(int common = 0; common <= prefix1 && common <= prefix2; i++) {
if(urls[start].charAt(common) != urls[end].charAt(common)) break;
}
return common;
}
Looking for interview experience sharing and mentors?
Visit A++ Coding Bootcamp at aonecode.com.
Taught by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greedy and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us aonecoding@gmail.com with any questions. Thanks!
Interviewer's solution to the 4th question
public int minUniqueSum(int[] A) {
int n = A.length;
int sum = A[0];
int prev = A[0];
for( int i = 1; i < n; i++ ) {
int curr = A[i];
if( prev >= curr ) {
curr = prev+1;
}
sum += curr;
prev = curr;
}
return sum;
}
Looking for interview experience sharing and mentors?
Visit A++ Coding Bootcamp at aonecode.com.
Taught by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greed and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us aonecoding@gmail.com with any questions. Thanks for reading.
interviewer's solution to 1st problem
public class CreateBinarySearchTree {
private TreeNode root;
public CreateBinarySearchTree() {
}
//create a BST on order of elements in the array
public CreateBinarySearchTree(int[] a) {
this();
for (int i : a) {
add(i);
}
}
private static class TreeNode {
TreeNode left;
int item;
TreeNode right;
TreeNode(TreeNode left, int item, TreeNode right) {
this.left = left;
this.right = right;
this.item = item;
}
}
public void add(int item) {
if (root == null) {
root = new TreeNode(null, item, null);
return;
}
TreeNode node = root;
while (true) {
if (item < node.item) {
if (node.left == null) {
node.left = new TreeNode(null, item, null);
break;
}
node = node.left;
} else {
if (node.right == null) {
node.right = new TreeNode(null, item, null);
break;
}
node = node.right;
}
}
}
public String toString() {
return toString(root);
}
private String toString(TreeNode node) {
if (node == null) {
return null;
}
return "[" + toString(node.left) + "," + node.item + "," + toString(node.right) + "]";
}
}
Looking for interview experience sharing and mentors?
Visit A++ Coding Bootcamp at aonecode.com.
Taught by experienced engineers/interviewers from FB, Google and Uber,
our ONE TO ONE courses cover everything in an interview including
latest interview questions sorted by companies,
SYSTEM DESIGN Courses (highly recommended for people interviewing with FLAG)
ALGORITHMS (conquer DP, Graph, Greed and other advanced algo problems),
and mock interviews.
Our students got offers from G, U, FB, Amz, Yahoo and other top companies after a few weeks of training.
Welcome to email us aonecoding@gmail.com with any questions. Thanks for reading.
Hi Nidhi,
Thanks for the inquiry. A few of our mentors are experienced backend data engineers. They can definitely guide you on the data architecture/warehousing area of the interviews. Please feel free to write to us aonecoding@gmail.com with any further questions.
Thanks!
RepDimaOxygen15, Computer Scientist at Headrun Technologies Pvt Ltd
Hi! all my sweets friends My name is Dimo Oxygen! Now I study in Victoria University of Wellington New Zealand ...
RepAmber Van is registered and fully insured cheap removal company in Bristol.Our featured services includes domestic moves,commercial moves ...
Repriverajenny935, i love my shop piano at xyz
Hello Everyone,My Name is Jenny Rivera .I have been a piano instructor for more than 25 years! I earned ...
RepAmber Van is the top rated company that offers friendly and professional removals services.Our featured services includes domestic moves ...
RepMartaLopes590, maintenence engineer at xyz
My name is Marta Lopes from Australia. I'm a single parent of one. I've been occupied with demonstrating ...
Repmethali0001, Frontend Software Engineer at Coupon Dunia
I am website designer in India Chandigarh. I done Msc in IT. I open a new small company for designing ...
RepVirginialdelmonte, Animator at lostlovebackvashikaran
Have you lost your husband love? And you want to control your husband mind with vashikaran mantra. Guru ji is ...
RepAre you wasting time for to search a professional astrologer and specialist to get rid of black magic?Black Magic ...
Open Chat in New Window
Looking for interview experience sharing and coaching?
Visit AONECODE.COM for private lessons by FB, Google and Uber engineers
Our ONE TO ONE class offers
SYSTEM DESIGN Courses (highly recommended for candidates of FB, LinkedIn, Amazon, Google & Uber etc.)
ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),
latest interview questions sorted by companies,
mock interviews.
Our students got hired from G, U, FB, Amazon, LinkedIn and other toptier companies after weeks of training.
Feel free to email us aonecoding@gmail.com with any questions. Thanks!
 aonecoding September 22, 2017