ajay.raj
 0of 0 votes
AnswersGiven k, and a binary string, determine if this contains all permutations of length k.
 ajay.raj in United States
For example, 11001 contains all possible binary sequences with k=2 (00,01,10,11) Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswerGiven a multiple tree, and multiple nodes that need to be deleted,
 ajay.raj in United States
It is required to return a list of nodes so that the children of these nodes can be found after the nodes have been deleted. Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersGives you an int m, and a set of char (0,1,2,3,4,5,6,7,8,9)
 ajay.raj in United States
Lets you implement a function that generates a id based on the characters in the set. Each time you return a string, it must be unique. satisfying the same character can not appear consecutively more than m times, such as m = 3, "1000" is valid,
"0000" is not valid.
The smaller the string, the better. Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswerTo push dominoes, find out how many dominoes are standing in the end
 ajay.raj in United States
For example, the input is ".R...RL..R..L..", which means pushing the 2nd, 6th, and 12th dominoes to the right and pushing the 8th and 15th dominoes to the left. This example returns 4th. 1,7,16,17 blocks are standing Report Duplicate  Flag
Amazon SDE1  1of 1 vote
AnswersThe question is that there are a lot of vm, what is the total vm consumption max. For example, (2,4,8), (3,5,3) this input,
 ajay.raj in United States
This means that 2 to 4 seconds have a memory usage of 8 and 3 to 5 seconds of 3, so the answer is 11 at 3 seconds.
Return 11 to it. Note that (1,2,3) and (2,3,4) such that the middle 3+4=7 is good.
Follow up is usage is not constant, such as (1,2,1,2) the first second usage is 1,
The second second is 2, the linear increase, the highest is how much. Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersGiven a list of tasks each with memory requirements and time, only one machine has K memory.
 ajay.raj in United States
Do not consider the context switch, page swap, virtual memory, (for example, the machine has only 20mb memory, a task that requires 25MB of the task can only wait until there is enough memory to run it.) The running task cannot be suspended.
Ask how long it takes to complete all these tasks. . . Report Duplicate  Flag
Amazon SDE1  0of 0 votes
Answers/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/Find the largest duplicate subtree in a binary tree For example, 1 / \ 2 3 / / \ 4 2 4 / 4 The following are two duplicate subtrees: 2 / 4 and 4
but the former is the largest, thus return the root of the first subtree
 ajay.raj in United States Report Duplicate  Flag
Amazon Software Engineer  0of 0 votes
AnswersGiven a target string, an input request replaces the word after the given index a>b such as:
 ajay.raj in United States
Target string: "Hello world!"
Input:{s:0, a:Hello b: Goodbye}
Output:"Goodbye world!".
The requirement is that input be given to several words that need to be changed at one time: {{s:0,a:Hello,b:Goodbye},{s:11,a:!,b:?},{s:6 a: World,b:friend}}
And each modified index is based on the original unmodified target string so the end result is
"Goodbye friend?" Report Duplicate  Flag
Amazon Software Engineer  0of 0 votes
Answersgiven a nary tree, find the total distance from this node to any other nodes
 ajay.raj in United States
class TreeNode {
int val;
List<TreeNode> children;
TreeNode(int val) {
this.val = val;
children = new ArrayList<>();
}
}
public int findDistance(TreeNode root, TreeNode node) {
} Report Duplicate  Flag
Amazon Software Engineer  1of 1 vote
AnswersHow many squares are inside a m*n rectangle where some grids in the rectangle were grey and the gray grid could not appear in the small squares.
 ajay.raj in United States Report Duplicate  Flag
Amazon SDE1  1of 1 vote
AnswersGiven an int array, check if all the numbers can be divided into 5 consecutive numbers.
 ajay.raj in United States
Eg: [1,2,2,3,3,4,4,5,5,6] Yes: (1,2,3,4,5) (2,3,4,5,6)
Followup: ask if you know that all the numbers are between 1 and 13,
what's a good optimization. Report Duplicate  Flag
Amazon SDE1  1of 1 vote
AnswerYou have two matrixs, how to move the first matrix
(move up, down, left, and right) so that the two matrix in the two matrixs match most.eg: matrix 1: matrix 2: 0 0 1 0 0 0 0 1 1 1 1 0 0 0 0 1 1 0
Then, after taking matrix1 (1 left shift + 1 down),
 ajay.raj in United States
the number of 1 in the match with matrix2 is 3 Report Duplicate  Flag
Amazon SDE1  0of 0 votes
Answershow to check if two graphs are structurally identical
 ajay.raj in United States
class UndirectedGraphNode {
List<UndirectedGraphNode> neighbors;
UndirectedGraphNode() {
neighbors = new ArrayList<>();
}
} Report Duplicate  Flag
Amazon SDE1  1of 1 vote
Answersconvert a Sorted array to complete BST
 ajay.raj in United States Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswerGive a connected graph, no cycle,
 ajay.raj in United States
Find the node where the average distance from all other nodes is the smallest Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswerInput: an int array without sorting, then do a binary search on it, and find the number of digits that cannot be found by binary search.
 ajay.raj in United States Report Duplicate  Flag
Amazon SDE1  0of 0 votes
Answers<key = "a"; val = "3"; depend_list = null;/>; <key = "b"; val = "a * a";
 ajay.raj in United States
Depend_list = {a};/>; <key = "c"; val = "a * b"; depend_list = {a,b};/>;
Lets output a map<key, value>,a > 3, b > 9, c > 27
Followup questions: Make a statistic for all keys and corresponding map entries with the same value. Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersGiven an array, find an x such that all numbers less than x are equal to themselves. Numbers greater than it are equal to x, and all numbers add up to a target
 ajay.raj in United States
For example, [1 3 5 7 9] target=24, answer is8. Because when x=8, the array has only 9>8, so 1+3+5+7+8=24 is the closest to the target. Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswerGive an Nlength array with only 0 and 1 inside
 ajay.raj in United States
Requires to find the minimum number of conversions needed to convert the array to 0 before all 1.
The conversion is to change a 0 to 1 or a 1 to 0,
And the number of 0 and 1 in the converted array can be arbitrary.
Just find the minimum conversion step Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersNumbers with 4 are considered to be unlucky, floor numbers are skipped with numbers with 4; for a top level n, ask how many layers there are actually; for example n=20, that is 18 levels [Remove 4, 14]
 ajay.raj in United States Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
AnswersInput unsorted integer array represents a list of coins,
 ajay.raj in United States
find the minimum amount of money that cannot be formed by these coins, each coin can only be used once
E.g. {1,1} > 3, {1,2,4} > 8 Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
AnswersGive me a list of int, find the length of the smallest cycle. For example, 1, 2, 1, 2, the length of the cycle is 2. Then 1, 2, 1, 2, 1 has a minimum length of 2. Then the length of 1, 2, 1, 2, 3 should be 5 because the entire list is not in repeat. Then the minimum length of 1, 2, 1, 2, 1, 1, 2 is 2.
 ajay.raj in United States Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswersFind the kth missing element in a sorted array. For example [2,3,5,7], k = 0: return 4, k = 1: return 6
 ajay.raj in United States
expected time complexity logn Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswersTo an array and K, each element in the array can only move K positions to the left at most, no limit to the right, try to sort the array under the limit of K
 ajay.raj in United States
a = [5, 2, 4, 3, 1], k = 2
Return [2, 3, 1, 4, 5] Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersGiven a function rand32() (random number range 02**321) that randomly generates a 32bit int, design a new random function:
 ajay.raj in United States
Randn(n) generates a random distributed random number (0  2**n1)
Rand3n(n) generates (0  3**n1) the uniformly distributed random number Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswerTopic: There is a set of coordinates. The original format of each coordinate is (1.3, 0.5). However, the comma and decimal point are gone. Only one string is left, allowing you to restore all possible combinations. For example, 123, possible (1, 23) (1, 2.3) (12, 3) (1.2, 3)
 ajay.raj in United States Report Duplicate  Flag
Amazon SDE1  0of 0 votes
Answersgiven period and threshold, Assume there is a endless streaming events, each event occurs at timestamp "x". The question want you to write an API that return true if number of the events are over the threshold within the period around timestamp "x"
 ajay.raj in United States
Ex:
period = 3, threshold =2
getEvent(10) > false
getEvent(12) > false
getEvent(13) > true [10,12,13]
getEvent(20) > false
part one: event come in order
part two: event come without order Report Duplicate  Flag
Amazon Software Developer  0of 0 votes
AnswersGiven vector<int> nums, and pair<int, int> range. Find out how many continuous subsequences within this vector sum up the number within the range.
 ajay.raj in United States
Input: [1, 2, 3], [3,6]
Output: (4)
because [1,2,3], [1,2], [2,3], [3] Report Duplicate  Flag
Amazon Software Developer  0of 0 votes
AnswerEach have a (x,y) coordinate.
 ajay.raj in United States
Write an API that group three Googler together for lunch if they are close enough. Otherwise, throw them in unschedule pool.
Distance formula = sqrt((x1x2) ^2 + (y1y2) ^2)
Given an int range;
Range: 2
Input  Output of API Unschedule pool
0,0 > [] [[0,0]]
1,0 > [] [[0,0], [1,0]]
3,0 > [] [[0,0], [1,0], [3,0]]
1,1> [[0,0], [1,0], [1,1]] [[3,0]] Report Duplicate  Flag
Amazon Software Developer  0of 0 votes
AnswersGiven an vector<int> nums and an int target, you can change any element of the vector to positive or negative. How many uniquely different vector sum up to target?
 ajay.raj in United States
Input: [1,1,1], target = 2
[1,1,1]
[1,1,1]
[1,1,1]
return (3) Report Duplicate  Flag
Amazon Software Developer  0of 0 votes
Answerfind max path sum in DAG, weight can be negative
 ajay.raj in United States Report Duplicate  Flag
Amazon Software Engineer  0of 0 votes
AnswersImplement a method to check if a nary tree is unival
 ajay.raj in United States
class TreeNode {
int val;
List<TreeNode> children;
TreeNode(int val) {
this.val = val;
children = new ArrayList<>();
}
} Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersGiven the length and width of a rectangle, how many ways can be used to go from the upper left corner to the upper right corner (each step can only go to the right, top right or bottom right):
 ajay.raj in United States
follow up 1: If three points in the rectangle must be visited, how many ways
follow up 2: If you are given an point H, and the path must go down below the H point, how to do it Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersThe thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms an nnary tree". It will automatically contact the police if two directlylinked houses were broken into on the same night.
 ajay.raj in United States
Determine the maximum amount of money the thief can rob tonight without alerting the police.
/**
* Definition for a nary tree node.
* public class TreeNode {
* int val;
* List<TreeNode> kids;
* }
*/
class Solution {
public int rob(TreeNode root) {
}
} Report Duplicate  Flag
Amazon SDE1  1of 1 vote
AnswerFor two string a, b, their distance is defined as the number of positions at which the corresponding character are different.
 ajay.raj in United States
Now you can swap characters at any two locations once, and ask how to swap to make the distance the smallest. Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
Answerspreorder Traversing a nary tree without using recurrsion
 ajay.raj in United States
TreeNode<T> {
T val;
List<TreeNode> children;
} Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersGiven two methods for the person class, one to find a dad and one to find a mother, using these two methods to achieve a method to determine whether the two people are related to blood, assuming a limited number of people.
 ajay.raj in United States Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersSelfimplemented data structures and methods, output all the heirs. To achieve birth (parent, name), dead (name), getAllSucession (). There is a king, you can use birth plus children, dead dead. The order of inheritance is the same as preorder except that this tree has multiple children.
 ajay.raj in United States Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswerA coffee machine has three buttons (S, M, L). After pressing each button, the coffee machine will flow out of a range of coffee [s1, s2], [m1, m2], [l1, l2], but the outflow of coffee The amount is random. There is a cup with a total capacity of c2. There is a tick c1 on the cup. If the amount of coffee is [c1, c2], it is considered full.
 ajay.raj in United States
After asking for a series of button operations, can the coffee be filled in [c1, c2] but not overflow? Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswersInput like method stack trace: "main, start", "foo, start", foo, end", "bar, start", "bar end", "main, end", "main2, start", "main2, end"
Output String, such as the following format, to indicate the order in which the method was called and the hierarchy
 ajay.raj in United Statesmain Foo Bar main2
 Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
Answerspublic TreeNode{
int val = val;
TreeNode left, right;
public TreeNode(int val){
this.val = val;
}
given a tree and an API, delete a part of the nodes in the tree and return the forest formed after the node is deleted.
public List<TreeNode> deletenodes(TreeNode root, List<TreeNode> toDeletes){
}
example
 ajay.raj in United States1 / \ 2 3 / / \ 4 5 6 If you delete the 2 and 5 nodes, you will need to return to the forest [4, 1] \ 3 \ 6
 Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
Answersturns the following format string into a tree: node has keys, values, and subtrees.
 ajay.raj in United States
For example, the first key is node1 and the value is ‘aaaa’
<node1>aaaaa<node2>bbbbb</node2><node3>cccc</node3><node4>dddd</node4></node1> Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
Answersfind longest common suffix of two linked list.
 ajay.raj in United States Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswersGive a 0/1 matrix to find and remove the islands. Assume that the boundaries of the matrix are 1
 ajay.raj in United States
The definition of islands is surrounded by 0
The simplest example is
enter:
111111
100001
100101
100001
111111
Output:
111111
100001
100001
100001
111111 Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswersWrite a hash function so that a string and its reverse get the same return value
 ajay.raj in United States
Hash(‘banana’) == hash(‘ananab’)
Hash(‘banana’) == hash(‘banana’)
Hash(‘banana’) != hash(‘banaaa’) Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
Answersx={a,b,c}, y={p,q}, z={r,s}
 ajay.raj in United States
Define a
Operation, x * y * z = {{a,p,r},{a,p,s},{a,q,r},{a,q,s}......{c,q s}}
Is to output all the results in the order of each subset, implementing a class iterator that has Next() and hasNext() methods Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswersGive a treelike graph that lets you find the maximum length from the leaf node to the leaf node. The input is an array of edges.
 ajay.raj in United States Report Duplicate  Flag
Amazon Backend Developer  1of 1 vote
AnswersTo determine whether two people have kinship, all data structures need their own definition
 ajay.raj in United States Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswerGiven an integer n (say somewhere between 100 and 1000), you want to generate a random binary tree having exactly n nodes. You are only interested in the structure of the tree. Each structurally unique tree should ideally have the same chance of being generated.
 ajay.raj in United States Report Duplicate  Flag
Amazon Backend Developer  1of 1 vote
AnswersGiven a binary matrix, find if there is a path from the upper left corner to the lower right corner, meet the conditions each time the value of the cell must be different.
 ajay.raj in United States
Follow up if there is a path with the same number of 0 and 1? Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersGiven k numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find sum of these k numbers.
 ajay.raj in United States
Example
S1 = “100”
S2 = “10”
S3 = “1”
Return “111”
public string addNumbers(String[] nums){
} Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswersThere is a process sequence that contains the start and end of each process. There is a query sequence asking how many processes are running at a certain point in time. Please return the query result of the query sequence.
 ajay.raj in United States
Example
Given logs = [[1, 1234], [2, 1234]], queries = [2], return [2].
Explanation:
There are 2 processes running at time 2.
Given logs = [[1, 1234], [2, 1234]], queries = [1, 1235], return [1, 0].
Explanation:
There is a process running at time 1, and 0 processes running at time 1235. Report Duplicate  Flag
Amazon Java Developer  1of 1 vote
AnswerGiven:
 ajay.raj in United States
R number of Red Cards
B number of Black cards
K
Cards needs to be placed in a circle. Start from a position and for
every K moves remove that card And
repeat the process until all the cards are eliminated.
Question: Position the cards such that the red cards are completely
eliminated before the blacks cards are selected for elimination. Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
AnswersGiven a BST convert it into new Data Structure that satisfies following conditions:
1. every leaf node's left ptr point to its parent and right ptr points to the next leaf
2. every non leaf node's left ptr points to its parent and right ptr is NULL
3. return the head and print the new DSexample: 7 / \ 5 9 / \ \ 4 6 10 output: head>4>5>7  >6>5>7  >10>97
with optimal time and space complexity
 ajay.raj in United States Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
Answersinput: "kitten%20pic.jpg"
 ajay.raj in United States
output: "kitten pic.jpg"
%20 > ' '
%3A > '?'
%3D > ':'
modify your input in place.
no string library functions.
void Decode(char[] str) Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
AnswersGiven a string T of length n, partition it in n' "phrases" (p1, p2, ..., pn'),
 ajay.raj in United States
such that
pi = pj + c, for some j<i, where + is string concatenation and c is a character
p0 = ''
p1 = pj + c where j < 1
T = p1 + p2 + ... + pn'
For example:
T = aababcabcd = a + ab + abc + abcd
p1 p2 p3 p4 Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
AnswersPrint a binary tree in vertical order using singly linked list...
 ajay.raj in United States Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
AnswerThere are three threads and we want them to run
 ajay.raj in United States
one after the other. How can we do that? Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersIn a grid, you are given a position, and every location has some value.
 ajay.raj in United States
find the shortest length so that you can touch to any boundary of the grid. Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersYou are given a graph and an algorithm that can find the shortest
 ajay.raj in United States
path between any two nodes
Now you have to find the second shortest path between same two nodes. Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswerFind product of distinct prime
 ajay.raj in United States
factor of all numbers .
Ex
10
12
7
prime factor of 10 = 2*5
prime factor of 12 = 2*2*3
prime factor of 7 = 7
SO distinct prime factor is 2*5*3*7 = 210 Report Duplicate  Flag
Amazon SDE1  0of 0 votes
Answersencode binary in bytes is to give a matrix of size M * N,
 ajay.raj in United States
This matrix is encoded in bytes as a 4 * 4 bool matrix
[0 0 0 0
1 0 0 1
0 0 0 0
0 0 0 1]
Will be encoded as a byte array [9, 1].
Then write a function set_one (vector <byte> arr, int M, int N, int start_row, int start_col, int end_row, int end_col);
Set all of 0 from (start_row, start_col) to (end_row, end_col) to 1
for example
start_row = 1
start_col = 2
end_row = 2
end_col = 0,
Just that 4 * 4matrix will become
[0 0 0 0
1 0 1 1
1 0 0 0
0 0 0 1]
The byte array after encode should be rewritten as [11, 129]. Report Duplicate  Flag
Amazon SDE1  0of 0 votes
Answersfind out all of the state machine will guaranteed to come to safe state
 ajay.raj in United States
ex
A > [B, C, D, E]
B > [A]
C > [D, E]
D > [E].
E > [safe state]
Output [C, D, E] because once these states will eventually go to safe state Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersWrite a simple RegEx parser function that handles only the
 ajay.raj in United States
operators * (0 or more) and + (1 or more), and returns true if
the provided string is a match. Signature:
boolean isMatch(String regex, String input).
Example: regex = a*b+ce, input = bce, return true
Example: regex = a*b+ce, input = ace, return false
Example: regex = a*b+ce, input = abcee, return false Report Duplicate  Flag
Amazon Software Engineer  0of 0 votes
AnswersGiven a tree and a number N,
 ajay.raj in United States
construct another tree such that each node of the tree has either 0 or
N elements,except for one node which has between 0 to N elements.
Only other constraint is
that ancestry is preserved in the new tree. Report Duplicate  Flag
Amazon Software Engineer  0of 0 votes
Answersgiven start and end of a given set of meetings, asking how to schedule
 ajay.raj in United States
as many meetings as possible。 Report Duplicate  Flag
Amazon Software Engineer  0of 0 votes
Answersfind a points that has same distance to given three points
 ajay.raj in United States Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
Answersinput is an int [] number is the car number parked in the parking lot, 0 for empty spaces
 ajay.raj in United States
Output is also an int [] requires a method to convert the input into target array.
Each car can only be exchanged with a 0. Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
Answers
 ajay.raj in United StatesGiven a string s1, we may represent it as a binary tree by partitioning it to two nonempty substrings recursively. Below is one possible representation of s1 = "great": great / \ gr eat / \ / \ g r e at / \ a t To scramble the string, we may choose any nonleaf node and swap its two children. For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat". rgeat / \ rg eat / \ / \ r g e at / \ a t We say that "rgeat" is a scrambled string of "great". Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae". rgtae / \ rg tae / \ / \ r g ta e / \ t a We say that "rgtae" is a scrambled string of "great". give a string s, print all the scrambled string of it class Solution { public List<String> ScrambleString(String s) { } }
 Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
AnswersThe problem is to count all the possible paths from any points to bottom right of a mXn matrix with the constraints that from each cell you can either move only to right or down
 ajay.raj in United States Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswerFind the final states of a nnary tree
 ajay.raj in United States
each node has three states, 0,1,2.
Require that if all child nodes are 2,
The parent node is also 2.
All child nodes are 0, the parent node is 0, and the rest are all 1s. Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswersGiven two functions, start (id, start_time), stop (id, time),
 ajay.raj in United States
Respectively, to the id assignment start and end time, gave a bunch of such operations (to ensure that the operation start small id first appeared,
And each id last have start_time and stop_time), press the start order to print the corresponding id, start_time, stop_time,
Requirements of space complexity as small as possible,
e.g., start (1, 1), start (2, 2), stop (2, 3), start (3, 4), stop
The print order is (1,1,6), (2,3,2), (3,4,5) # (id, start_time, end_time). Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswerTo several bus lines, each line is a twoway line, such as:
 ajay.raj in United States
0: A <> B <> D
1: C <> D
After writing the map, give you a start and end, let me find the path through the least station. Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswerOutput the second index corresponding to the first one, requiring output only if there is only one match, and false if there is more than one pair
 ajay.raj in United States
a b c d e f g a b > [0,1]
a b b c, a b c > False Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswersCheck if characters of a given string can be swaped to form target string
 ajay.raj in United States
ab : ba true
ac : ab false Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
Answers1 \ 2  3 \ / 4  5  8  / 7 For the undirected graph, the LCS is 2,3,4,5, so how can we find it? For a undirected graph, find the Longest Consecutive Sequence
/**
 ajay.raj in United States
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public List<Integer> longestGraph(List<UndirectedGraphNode> nodes) {
}
} Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
Answerscheck if there are two subarrays in an array are identical
 ajay.raj in United States Report Duplicate  Flag
Google Backend Developer  0of 0 votes
Answerscomparison of two strings if they are the same, use o(1) space
 ajay.raj in United States
abc \ b is equal to ab
abc \ ca equals abcA
\ b = backspace
\ c = CapsLock Report Duplicate  Flag
Google Backend Developer  0of 0 votes
Answerconvert Prefix to Postfix using recursion
 ajay.raj in United States
+ * A B / C D > A B * C D / + Report Duplicate  Flag
Google Backend Developer  0of 0 votes
AnswersDesign a dictionary with historical records
 ajay.raj in United States
t0: hdict = HistoricalDict ()
t2: hdict.set ('foo', 1)
t4: hdict.set ('foo', 2)
t5: hdict.get ('foo', t5) > 2
t6: hdict.get ('foo', t3) > 1
t7: hdict.get ('foo', t0) > None Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswersCSS colors can be defined in the hexadecimal notation "#rgb", a shorthand for "#rrggbb". For example, "#03f" is equivalent to "#0033ff". Suppose the similarity between two colors "#abcdef" and "#ghijkl" is defined as ((abgh)^2  (cdij)^2  (efkl)^2), write a function that accepts a color in the "#abcdef" format and returns a "#rgb" color that is most similar to the input. For example, given "#09f166", "#1e6" should be returned.
 ajay.raj in United States Report Duplicate  Flag
Google Java Developer  0of 0 votes
Answers
 ajay.raj in United StatesGiven a binary tree, output the maximum EVEN sum along any path 10 / \ 2 5 / \ \ 1 101 13 Maximum even sum = 101 +2 +10 + 5 = 118
 Report Duplicate  Flag
Google Java Developer  0of 0 votes
Answersconvert a Sorted linkedList to complete BST
 ajay.raj in United States Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswersGive N socks, there is no guarantee that each can be paired, socks two colors, black and white, you need to pair them
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
Answerscss color format # abcdef, another abbreviated color format # rgb
 ajay.raj in United States
(Converted to the previous format, ie, #rrggbb.) Now give your #abcdef, the first color format, to find the two least different colors, #rgb. Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGiven list of edge in the graph, find the number of reversed pairs,(1,2)
 ajay.raj in United States
and (2,1) are such pair. Follow up: How to implement the distributed version. Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswersAn n * m matrix represents an array of computers, giving you a List <int []> that represents the coordinates of the broken computer.
 ajay.raj in United States
Now we start from (0,0) repair computer requirements:
1. You must finish all the broken computers in the current line to get to the next line
2. To go to the next line, the mechanic must first return to the far left or right of this line
And then find repair each computer order that has the minimum access distance, Report Duplicate  Flag
Google Java Developer  1of 1 vote
AnswersA robot can only be moved one step to the right (x + 1) at a time while moving upward or downward or horizontally (y1, y + 1, y) , given the starting and ending positions, and a series of points must pass, ask how many kinds of ways from start to end.
 ajay.raj in United States Report Duplicate  Flag
Google Java Developer  1of 1 vote
AnswersFind if the shorter string is a subsequence of the longer string
 ajay.raj in United States
Output the second index corresponding to the first one, requiring output only If there is only one match, and false if there is more than one pair
a b c d e f g, a b > [0,1]
a b b c, ab c > False Report Duplicate  Flag
Google Backend Developer  1of 1 vote
AnswerTo several bus lines, each line is a twoway line, such as:
 ajay.raj in United States
0: A <> B <> D
1: C <> D
give you a start and end, find the path through the least station. followup
Asked the least transfer case Report Duplicate  Flag
Google Backend Developer  1of 1 vote
AnswersDetermine whether the inorder of n binary trees is the same
 ajay.raj in United States Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswersGive you a csv file There are three columns are id, parent, weight Then give you a class Node which has these three fields
 ajay.raj in United States
But you also have the option of adding more fields for you to print out all the node's subwebs.
The definition of subweight is the sum of the node's weight plus the subweight of his children. Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswersGive a chessboard, check if a group of white chesses are surrounded by all black chesses.
 ajay.raj in United States Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswersGiven a list of relationship of report
 ajay.raj in United States
A reported to D, D reported to Z, who are reported to Z Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswersGive the structure of a directed graph
 ajay.raj in United States
START > a > b > c > END
If a word can start from start and end at END, then we think the word is in this diagram
For example, the string "abc" is consistent, but "ab" does not match,
Although "ab" is also inside the graph, b's next is "c" instead of END, so it's not legal word
(Note: each node can have more than one next)
1. According to the problem, design the data structure
Write a function, input is START and a string, to determine whether the string is a valid word
3. follow up, if the graph has cycle, how to do?
4. If the graph has repeated characters how to do? Report Duplicate  Flag
Google Java Developer  0of 0 votes
Answershow to check is a small matrix appear in a big matrix
 ajay.raj in United States
boolean isSubmatrix(int[][] small, int[][] big) Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswersYou have to cut a wood stick into pieces. The most affordable company, The Analog Cutting Machinery,
 ajay.raj in United States
Inc. (ACM), charges money according to the length of the stick being cut. Their procedure of work
requires that they only make one cut at a time.
It is easy to notice that different selections in the order of cutting can led to different prices. For
example, consider a stick of length 10 meters that has to be cut at 2, 4 and 7 meters from one end.
There are several choices. One can be cutting first at 2, then at 4, then at 7. This leads to a price
of 10 + 8 + 6 = 24 because the first stick was of 10 meters, the resulting of 8 and the last one of 6.
Another choice could be cutting at 4, then at 2, then at 7. This would lead to a price of 10 + 4 + 6 =
20, which is a better price.
Your boss trusts your computer abilities to find out the minimum cost for cutting a given stick. Report Duplicate  Flag
Google Java Developer  1of 1 vote
AnswersGiven an aray with ['a1', 'a2', .....'aN', 'b1', 'b2', ....'bN', 'c1', 'c2', .....'cN'],
 ajay.raj in United States
stagger the subarrays so it becomes ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', ...'aN', 'bN', 'cN']. The optimal solution requires lineartime
sorting and a constant space complexity. Report Duplicate  Flag
Facebook Java Developer  0of 0 votes
AnswerHow to design a spreadsheet program? How do you know to update a field after another
 ajay.raj in United States
field was changed that it depended on? Report Duplicate  Flag
Facebook Java Developer  0of 0 votes
AnswersGiven a set of points in the 2D coordinate system, find the radius of the
 ajay.raj in United States
smallest circle which encompasses
all the given points Report Duplicate  Flag
Facebook Java Developer  0of 0 votes
AnswersTry to come up with a combination of two data structures to implement a
 ajay.raj in United States
data structure that supports search,
delete in O(1) time and insert in O(n) time.Try to come up with a combination of two data structures to implement a
data structure that supports search,
delete in O(1) time and insert in O(n) time. Report Duplicate  Flag
Facebook Java Developer  0of 0 votes
AnswersA sequence of strings, printed first by column, on a screen of width K,
 ajay.raj in United States
Requires the first column of the same column by column alignment,
At least one character interval between columns and columns,
Ask how many lines at least?
such as:
The string sequence is {"abc", "de", "fghij", "k", "lmno", "p"}
The screen width is 10
The answer is at least 3 lines
abc k
de lmno
fghij p Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGive a decimal number, such as 123. Asking a total of smaller num than 123 made up by 1 and 0 composed of decimal numbers.
 ajay.raj in United States
111, 110, 101, 100, 11, 10, 1, 0. Report Duplicate  Flag
Google Software Engineer  0of 0 votes
AnswersTo a word, and a map, map which is a word, ask this if a word is smash able? That is, you can smash one letter each time, and the rest of the letters can form a single word (the new word is still in the map) until it is completely hit.
 ajay.raj in United States
For example: sprint > print > pint > pit > it > i > "" Report Duplicate  Flag
Google Software Engineer  2of 2 votes
AnswersMinimum number of swaps of chars in only one string to make two strings the same
 ajay.raj in United States Report Duplicate  Flag
Google Software Engineer  0of 0 votes
Answers
 ajay.raj in United StatesMatrix conversion problem. For example, give a matrix a: 1, b: 2. b: 2, c: 3 Then converted into a, b, c 1, 2, . ., 2,3
 Report Duplicate  Flag
Google Backend Developer  0of 0 votes
AnswersImplement a greplike function. For example
 ajay.raj in United States
[A1 + A2, B1 + B2, C1], grep (A = A1), is to return the result that contains A1,
For example, [A1, B1, C1], [A1, B2, C1].
More tricky can be grep (A = A1, A2, B = B1), so that is included (A1  A2) & B1. Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswersGiven an array {a0, a1, a2, ... an, b0, b1, b2 ... bn},
 ajay.raj in United States
Rearrange this array into {a0, b0, a1, b1, a2, b2, ... an, bn}
inplace, O (1) space Report Duplicate  Flag
Google Java Developer  1of 1 vote
AnswerSuppose there is a map with N bikes on it and now we have N individuals,
 ajay.raj in United States
Design an algorithm so that everyone can get the bike in the shortest distance Report Duplicate  Flag
Google Android Engineer  0of 0 votes
AnswersGiven a string, at each time, you can move any one of the char to the front,
 ajay.raj in United States
ask you to find the minimum such move to get the target string
example
source abc, target cba :
abc > bac > cba
return 2 Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGive you a bunch of light bulbs. Can flip a range of open change off, turn off open, and then asked to do so k times later, just ask you a light bulb is turned on or turned off, how to do
 ajay.raj in United States Report Duplicate  Flag
Google Java Developer  0of 0 votes
Answer*e*er > peter
 ajay.raj in United States
**eue > queue
**o
ma*
*p*a*e*
*erso*
***k*am*on
*ouse
*a*
*ur*
***igent
where there are 26 *, and we can fill all the stars in to form valid english words while using each letter once. Given this array and a dictionary how would you fill all the words in? Report Duplicate  Flag
Google Java Developer  2of 2 votes
Answerspublic string stringWrap (String text, int characters)
text is an input string, characters on behalf of the output of
each line up to the number of bytes
input
 ajay.raj in United States"Thank you for shopping at the XYZ store.\n Your order has been processed successfully.\n", 20 output： "Thank you for\n shopping at the XYZ\n store.\n Your order has been\n processed\n Successfully.\n" example 2:"Hello! How are you?"，6 output “Hello!\n How\n are\n you?\n"
 Report Duplicate  Flag
Google Java Developer  1of 1 vote
AnswersGive a string [] words,
 ajay.raj in United States
Find the shortest string [] containing the keyword inside.
example:
words: sky cloud google search sky work blue
keywords: sky blue
return: sky work blue Report Duplicate  Flag
Google Principal Software Engineer  1of 1 vote
AnswerGiven an array, find the number of tuple such that A [i] + A [j] + A [k] = A [l] in an array, where i <j <k <l.
 ajay.raj in United States Report Duplicate  Flag
Google Data Engineer  1of 1 vote
AnswerGiven a nnary tree, check whether it is a mirror of itself (ie, symmetric around its center).
 ajay.raj in United States
class TreeNode {
int val;
List<TreeNode> children;
TreeNode(int val) {
this.val = val;
children = new ArrayList<>();
}
} Report Duplicate  Flag
Google Jr. Software Engineer  2of 2 votes
AnswerImagine a scenario where there are N cars on an infinitely long singlelane road. Each car has a unique, permanent integer speed ranging between 1 and N, inclusive (units are irrelevant). The cars can be placed in any order along the road and then told to start driving indefinitely. Let's assume that the cars are traveling from righttoleft. So the leftmost car is at the front. Given an ordering of N cars, construct an algorithm to return an array of cluster sizes
 ajay.raj in United States
N=4
[2, 4, 1, 3] > [2, 2]
[2, 5, 4, 3, 1] > [4, 1]
followup：
New car speed = N+1. Given an ordering of N cars, construct an algorithm to return an array of arrays of cluster sizes that will arise when the N+1 car is inserted. The ith row in the outer array corresponds to the cluster sizes that exist when the N+1 car is inserted into the ith index
new car speed = 5
[2, 4, 1, 3] > [[1, 2, 2], [3, 2], [3, 2], [2, 3], [2, 3]] Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswersGiven one string s1, and then insert one char into this string at any place, to get s2, find the inserted char
 ajay.raj in United States
Could you do it in logn time Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGive you a 2xN board and two kinds of tiles: 1x2 (two squares across), 2x1 (two squares up) Ask how many ways you can fill the board.
** ** * * * * ** **
Follow up is the new four kinds of tiles: L shape in different angle, , ask you how many kinds of tiles are now six
 ajay.raj in United States Report Duplicate  Flag
Google Data Engineer  0of 0 votes
Answersgive a binary matrix, 0 on behalf of the sea, 1 on behalf of the land, the val also represents the height of the altitude, if a cell is originally on land and is also surrounded by eight neighbor are on land, that cell become 2, each cell and its eight neighbor elevation cannot differ by more than 1. Return to the highest altitude can take altitude (special case is if the entire matrix is 1, then it is unlimited)
 ajay.raj in United States Report Duplicate  Flag
Google Data Engineer  0of 0 votes
AnswerIn the range of 0n, return all the numbers that in the reverse can be mistaken for another number. E.g. 18 > 81. The corner case is not counting the same number, such as 101 and not 0 at the end of the figure such as 60 (because 09 is not 9)
 ajay.raj in United States
Public List<Integer> getNum(int n) Report Duplicate  Flag
Google Backend Developer  0of 0 votes
AnswerGive a binary tree, each node has an extra information, that is, how many children he has,
Find the kth node val in the inorder transversal ,
Followup how to insert a node, such that this newly added node become the Nth node of the inorder binary tree's traversal
 ajay.raj in United Statesclass TreeNode{ int val; int NumberOfchildren; TreeNode left; TreeNode right; public TreeNode(int val){ this.val = val; } } public static int findKthOfInorder(TreeNode root, int k) {
 Report Duplicate  Flag
Google Backend Developer  0of 0 votes
AnswersGive a weighted nnary tree and find the longest path from the root node to the leaf node
 ajay.raj in United States
class Node {
int id;
// connected node id, edge weight
Map <Integer, Integer> edges;
} Report Duplicate  Flag
Google Data Engineer  0of 0 votes
AnswersGiven a binary matrix, count the number of square that can be formed by all 0s
 ajay.raj in United States Report Duplicate  Flag
Google Data Engineer  0of 0 votes
Answersgiven a string p, called order, such as abc, means a in front of b, and so on
 ajay.raj in United States
given a second string s, to determine whether it is follow the order of p, return boolean,
example If aaa return true,
If cba is false
If aaxyc is true, the letters that have not been seen in the order are skipped Report Duplicate  Flag
Google Data Engineer  0of 0 votes
AnswersGiven a string as a datastream Iterator<Character>, find the length of the longest substring without repeating characters
 ajay.raj in United States
public String longestUniqueChars(Iterator<Character> chars) Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswerGiving start string and end string, determine if start string can finally reach to the same as end string with below rules.
 ajay.raj in United States
For example:
"R L _ _ L R L"
"_": the space is empty
"L": this can only swap with the empty letter _ on its left side
"R": this can only swap with the empty letter _ on its right side
So, "R L _ _ L R L" can change to "R L _ L _ R L" , and can continue change to (if you want) "R L L _ _ R L". from: 1point3acres.com/bbs
The question is given these rules and the start string and end string, could we change the start string to end string (unlimited # moves as long as it is valid).
For example:
"R _ _ L R _ R _L"
can be changed to
"_ R L _ _ R R L _" Report Duplicate  Flag
Google Java Developer  1of 3 votes
Answersgiven a list of points in a rectangular coordinate system, seeking any two points, such that all the remaining points will be in only one side of the line.
 ajay.raj in United States Report Duplicate  Flag
Google Java Developer  1of 1 vote
AnswerGiven a MxN matrix where each element can either be 0 or 1. We need to print the shortest path between a given source cell to a destination cell. The path can only be created out of a cell if its value is 1.
 ajay.raj in United States
BFS is trival, please solve it use DFS
public void print(int[][] matrix, int[] start, int[] end){
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGive a string, finds all duplicate substrings of length k
 ajay.raj in United States Report Duplicate  Flag
Google Backend Developer  2of 2 votes
AnswerGive an array such as [1,2,2,2,0] every time you can jump 1 to a [i] step,
 ajay.raj in United States
If you can jump to 0, return false
if you go out to return true Report Duplicate  Flag
Google Backend Developer  0of 0 votes
AnswerA group of people goes to eat together, each pay is not the same, then after they go home later, they each use mutual transfer so that everyone pay the same money.
 ajay.raj in United States
input is an int array that each person pay, Ask who the amount of money was paid when the transfer was done, such as B > A $ 3, C > A $ 1. Report Duplicate  Flag
Google Backend Developer  0of 0 votes
Answersfind the last index of the last duplicate number in a sorted array
 ajay.raj in United States
ex
input: 1,2,5,6,6,7,9
output: 4(index) Report Duplicate  Flag
Google Backend Developer  0of 0 votes
AnswersGiven a string, check if it is can be reorganized such that the same char is not next to each other, If possible, output a possible result
 ajay.raj in United States
example
input: google
one possible output: gogole Report Duplicate  Flag
Google Backend Developer  0of 0 votes
AnswersGiven a nonempty string s, you may delete at most k characters. Judge whether you can make it a palindrome.
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswerGiven a dictionary, generate the shortest string, both palindrome and pangram.
 ajay.raj in United States
Each word can be used only once and unlimited words can be used. Report Duplicate  Flag
Google SDE1  1of 1 vote
AnswersGive you a pattern (digit in the pattern matches the corresponding
 ajay.raj in United States
number of letters,
letter means match the letter itself),
a string to determine whether match:
ex:
abc > 'abc' true
'1oc3' > 'aoczzz', 'bocabc' true Report Duplicate  Flag
Google SDE1  0of 0 votes
Answersassuming there is a freeway, n cars on the road, each car has a different integer speed, but are in the 1n range. Now give you an array that represents the speed of each car. The starting order of the vehicle is the order of the array, ask the final formation of several clusters, the size of each cluster is how much? It can be understood that, although the vehicle speed is different, but even behind the car faster than the previous car, because you cannot pass, the last must only travel at the speed of the previous car, which formed a cluster. For example [2,4,1,3], finally [2,4] is a cluster, [1,3] is a cluster.
 ajay.raj in United States
Follow up is now suppose you want to add a car, the speed of the car than other large, but not sure the car's starting order, so that the final output of each possible cluster (List of List). Requirements can be adjusted and call the previous function, but can only be called once Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersThere is a stream of data <Symbol, timestamp, price>, and possibly also Correction Data <Symbol, timestamp, price> and then addData (symbol, timestamp, price) and correctData , Update minPrice, maxPrice, recentPrice in these two functions.
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswerGive you a bunch of data <key, value, expiredTime>, design a data structure storage.
 ajay.raj in United States
About the idea, based on Map solution.
class NewMap {
Map <Integer, Integer> data = new HashMap <> (); // store keyvalue pairs
Map <Integer, Integer> expired = new HashMap <> (); // store keyexpired pairs
}
Then implement the three functions get (), put (), expire (). Report Duplicate  Flag
Google SDE1  0of 0 votes
Answershow to implement the standard JSON.stringify and JSON.parse method
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersFibonacci asked if you want to query 12 ^ 32 any one but the memory can only remember 2 ^ 20 number of how to do O (1) query
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
Answerson a bench, sitting a number of people, and now come up a person, how to find a seat that is farthest from other people,
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
Answers0 change to 01,1 change to 10.
 ajay.raj in United States
Line 0 is 0, the first line is 01, the second line is 0110, the third line 01101001. . . Keep asking what is the vale at kth row and jth col Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersAssuming your budget is N, you need to buy a rectangular land. Give a matrix of land prices and ask what is the largest area available for buying land. Land prices must be nonnegative. For example, the budget is 11.
1 2 3 1 0 1 4 2 1 9 10 4 The output should be. 1 2 3 0 1 4
Such a matrix, because 1 +2 +3 +0 +1 +4 = 11. And the largest area.
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  1of 1 vote
AnswersThe grid is n by m. Each cell contains a unique number on it. Maga is at the lefttop and wants to go to rightbottom. But there is a condition. Maga can go through only two way  right and down. And the path of your move is called the nodes you have passed through over them. The path is called the most beautiful if the following condition is satisfied: The sorted of the path has to be lexicographic smallest as possible as. Output the most beautiful path for given grid.
Input:
In the first line you are given two numbers: the dimensions of grid  n and m. The next n lines contains m numbers. Each number is unique.
Output:
Output the most beautiful path.4 2 3 1
Return 1 2 4
 ajay.raj in United States
There are 2 ways to reach at (2,2) cell. The pathes are 4, 3, 1 or 4, 2, 1 respectively. So The most beautiful of them is 4, 2, 1 because if looking the sorted of them it looks like these : 1, 3, 4 and 1, 2, 4 respectively. So 1, 2, 4 is lexicographic smaller than the other. So the ans is 1 2 4. Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersTwo binary tree, to determine whether the two trees "similar", similar refers to the corresponding node in each tree in the left child and right child can be the same or in the opposite order, such as the following two trees, D, E where DE And DE can also be DE and ED, BC is the same, but the parent child relationship must be the same.
Followup is if left and right can be the same how to do,
 ajay.raj in United StatesA / \ B C / \ D E A / \ C B / \ D E
 Report Duplicate  Flag
Google SDE1  0of 0 votes
Answersgiven n player competition, a bool canbeat (int a, int b) can return a whether beat b. Asked to return a sequence, the sequence only requires two adjacent to the front beat behind. Example, 1 beat 2, 2 beat 3, 3 beat 4, 3 beat 1, 4 beat 1 You can return "1234", that is, although 3,4 can beat 1, but not adjacent does not matter
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGive a twodimensional array, which represents the value of the jump to the four directions, asked whether from the upper left corner to the lower right corner, follow up the shortest distance
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersTo A and B two list, B is A shuffle obtained, find the mapping used shuffle,
 ajay.raj in United States
To be able to handle duplicate elements.
Followup: Requirements space O (1), Report Duplicate  Flag
Google SDE1  0of 0 votes
Answerslist, push is pushed to the head, pop return each element with the same probability. If you push a sorted list into it, how to pop a sorted list out. Followup, asked if pop is from head, and push each element with the same probability in any position, how pop a sorted list out?
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersDetermines whether two strings containing backspace keys are the same.
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersA car can receive two instructions A and R. A moves forward for a second and then doubles in speed. R stopped and then reversed. Given a String composed of AR, find where will the car stop.
 ajay.raj in United States
Followup, given the location if the final stop, find the instruction string. Report Duplicate  Flag
Google SDE1  1of 1 vote
Answersclass EncodingChecker {
 ajay.raj in United States
EncodingChecker (String pattern) {...} // constructor
boolean isEncoded (String s) {...} // for any string s, check whether s is encoded from pattern, see below
}
pattern = 'abcabc'
s = '123123' > True
= 'cbzabc' > False
= 'xyzxyz' > True
Second question: If the pattern is not one but one million, how to write isEncoded? Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersFind the maximum sum of subset of size K in an array
 ajay.raj in United States Report Duplicate  Flag
Facebook Developer Program Engineer  1of 1 vote
AnswersDefine a flight class, the flight has four attributes start, end, start time and arrival time,
 ajay.raj in United States
There is also a list of strings, represents there is a crew member on that site.
given a list of flights, along with the list of strings mentioned above, asking if the flight crew availability is available for all flights.
example: flight 1 {A, B, 3, 10}, flight 2 {A, C, 1, 7}, flight 3 {C, D, 9, 11} crew member list {"A", "A"} Then return true because flight 3 can take off as flight 1 and flight 2 take off first, then flight 2 descends to bring flight crew A to C.
If flight 3 is {C, D, 6, 12} then return false because no flight crew member is in C at time 6. Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGiven an array (may have negative num) and an integer(may be negative), find the smallest subarray whose sum is >= the given integer.
 ajay.raj in United States
int[] nums2 = {5,4,8,16};
int x=10;
return 1, because 16 >= x
try to solve it in o(n) time
public static int miniSubArrayLen(int[] nums, int s) { Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersYou are given a binary tree in which each node contains an integer value.
 ajay.raj in United States
Find the number of paths that sum to a given value.
The path does not need to start at root, but need to end at a leaf, and it must go downwards (traveling only from parent nodes to child nodes).
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int pathSum(TreeNode root, int sum) {
}
} Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGive a bunch of rectangles, randomly return a point within the rectangle, the probability to be proportional to the size of the rectangle.
 ajay.raj in United States
Follow up1: If you want to repeatedly call the function to generate random points how to do.
Follow up2: If the rectangles overlap how to do? Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersMagical binary strings are nonempty binary strings if the following two conditions are true:
 ajay.raj in United States
The number of 0's is equal to the number of 1's.
For every prefix of the binary string, the number of 1's should not be less than the number of 0's.
A magical string can contain multiple magical substrings. If two consecutive substrings are magical, then we can swap the substrings as long as the resulting string is still a magical string. Given a magical binary string, str, perform zero or more swap operations on its consecutive magical substrings such that the resulting string is aslexicographically large as possible. Two substrings are considered to be consecutive if the last character of the first substring occurs exactly one index before the first character of the second substring.

Input Format
a single binary string, str.
Constraints
It is guaranteed that str is a binary string of 1's and 0's only.
1 ≤ length(str) ≤ 50
It is guaranteed that str is a magical string.
Output Format
Find a string denoting the lexicographically largest magical string that can be formed from str.
Sample Input 0
11011000
Sample output
11100100
Explanation of sample
Given the magical string str = 11011000, we can choose two consecutive magical substrings, 1100 and 10, to swap such that the resultant string, str' = 11100100, is the lexicographically largest possible magical string possible. Thus, we return the value of str', which is 11100100, as our answer. Report Duplicate  Flag
SDE1  0of 2 votes
AnswersGiven a matrix of each element is the height of the location, the side of the matrix has a river height h, water diffuse matrix results,
 ajay.raj in United States
Follow up If there is a place where there is not drowning a person and a dog, people want to reach the dog's position without water, the river is highly uncertain,
Ask the maximum height h such that the number of steps taken by a person is less than or equal to a given k. Traverse the height h, Report Duplicate  Flag
Google Software Engineer  0of 0 votes
AnswersQuestion: Given a sorted integer array, return sum of array so that each element is unique by adding some numbers to duplicate elements so that sum of unique elements is minimum.
 ajay.raj in United States
I.e., if all elements in the array are unique, return the sum. If some elements are duplicates, then increment them to make sure all elements are unique so that the sum of these unique elements is minimum.
Some examples:
input1[] = { 2, 3, 4, 5 } => return 19 = 2+3+4+5 (all elements are unique, so just add them up)
input2[] = { 1, 2, 2 } => return 6 = 1+2+3 (index 2 is duplicate, so increment it)
input3[] = { 2, 2, 4, 5 } => return 14 = 2+3+4+5 (index 1 is duplicate, so increment it) Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersMr. Octopus has recently shut down hisfactory and want to sell off his metal rods to a local businessman.
 ajay.raj in United States
In order to maximize profit, he should sellthe metal of same size and shape. If he sells metal rods of length ,he receives N x L xmetal_price. The remaining smallermetal rods will be thrown away. To cut the metal rods, he needs to pay cost_per_cut for every cut.
What is the maximum amount of money Mr.Octopus can make?
Input Format
First line of input contains cost_per_cut
Second line of input contains metal_price
Third line contains L, the number of rods Mr. Octopus has,followed by L integers in each line representinglength of each rod.
Output Format
Print the result corresponding to the testcase.
Constraints
1 <= metal_price, cost_per_cut <= 1000
1 <= L <= 50
Each element of lenghts will lie in range [1, 10000].
Sample Input#00
1
10
3
26
103
59
Sample Output#00
1770
Explanation Here cuts are pretty cheap. So we can make largenumber of cuts to reduce the amount of wood wasted. Most optimal lengths ofrods will be . So we will cut pieces of length from rod,and throw peice of length from it. Similarly we will cut piecesof length from rod and throw away a piece of length .From rod, we will cut pieces of length andthrow a piece of length . So in total we have pieces of length andwe have made cuts also. So total profit is
Sample Input#01
100
10
3
26
103
59
Sample Output#01
1230 Report Duplicate  Flag
coursea SDE1  2of 2 votes
Answersgiven two strings a and b.
 ajay.raj in United States
print out the minimum number of flips of the characters in a such
that a is an anagram of b. Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersJSON parsing is an essential toolkit in modern web development. Whether you are on the client side or server side, these methods need to be fast, efficient and dependable. But what if one day...
 ajay.raj in United States
Suddenly, all of the JSON parser libraries went missing.
You have been called upon to save us all from impending doom.
Please reimplement the standard json parsing methods in your favorite language and restore the world to it's natural order.
Subproblem #1
Write a function, dictionaryToJson to convert a dictionary into a string.
For example, assuming you have dictionary like: dict(“a”: “apple”, “b”: dict(“b”: “blueberry”, “c”: “cranberry”)), the key field is always a string type, the value field could be a string type or a nested dictionary type. And the output would be "{a:apple,b:{b:blueberry,c:cranberry}}"
Subproblem #2
Write a reverse function, jsonToDictionary to convert a string into a dictionary.
Convert a string into the dictionary. e.g., given the input of “{a:apple,b:{b:blueberry,c:cranberry}}”, output dict(“a”: “apple”, “b”: dict(“b”: “blueberry”, “c”: “cranberry”)).
The names and values only contains letters. You can assume that there is no error in the input. You should not use regular expressions. Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersTo a binary array, if you want to move 1 to the array side, 0 to the other side, Can only swap two adjacent elements each time, ask the least number of swap Why? For example, the number of min swaps for [0, 1, 1, 0, 0] is 2 (01100 > 10100 > 11000)
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersbalanceSum, return to the array to meet the minimum sum equal to the minimum index. Title conditions are all positive numbers, the array length> = 3, there must be solution. If a = [1,2,1,3] returns 3 because a [1] + a [2] = a [4]
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswerGive a string that outputs the largest alphabetical order of all consecutive substrings For example, "ab", substring has {"a", "ab", "b"}, output "b"
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
Answersstream reading number, with timestamp, Design data structure to know the minimum value of the past year, the average,
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
Answerssorting nested dictionaries
 ajay.raj in United States
give a
{b: {cb: cranberry, bb: blueberry} a: apple, c: cherry}
{a: apple, b: {bb: blueberry, cb: cranberry}, c: cherry}
To sort the key output, if there is nested dictionaries, but also to sort Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersIf xi<xj,yi<yj, we say (xj,yj)dominates(xi,yi). Given a set of number pairs (xi,yi),
 ajay.raj in United States
how many indomitable pairs are there? Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersMark likes to listen to music while travelling. His iPod™ contains
 ajay.raj in United States
N songs and he wants to listen to L (not necessarily different) songs during
a trip. So he creates a playlist such that:
• Every song is played at least once.
• A song can be played again only if at least K other songs have been played
Mark wants to know how many different playlists are possible. Can you help Mark determine this number?
As the number can be very large,
display number modulo 1,000,000,007.
You are given N, K and L. Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGiven the width, height, start point, end point of the grid, and a list of points, you have to go through these points, ask how many paths are there from the start point to the end point, you can only move from (i, j) down and right.
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  1of 1 vote
AnswerThe design of two functions, cyclecount (num, mod), cycleHistogram (low, high, mod). Probably, cyclecount (num, mod) do digits square sum mod operation. For example mod (12), mod (5) > square (1) + square (2) mod 5 = 0 > square (0) mod 5 = 0. Stop return 2. Finished digits square sum after take mod, mod and before the formation of a repetitive cycle. Return form the size before the cycle. CycleHistogram (low, high, mod) will give a [low, high]. Then return a histogram which stores the number of [low, high] inside the cycle size 1,2,3,4,5.
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
Answersfind LCA in directed acyclic graph
 ajay.raj in United States
class Node {
int label;
List<Node> neighbors;
Node(int x) {
label = x;
neighbors = new ArrayList<>();
}
}
public List<Node> findLCAINDAG(Node, graph, Node n1, Node n2) Report Duplicate  Flag
Facebook SDE1  2of 2 votes
AnswersThere is a set, there are some balls, different balls have different weights, for example: [red ball 4, yellow ball 1, green ball 2, blue ball 2]
 ajay.raj in United States
Ask for the first kweight combination in this case, if k is 5 then:.
[Red, yellow, green, blue] 9
[Red, green, blue] 8
[Red, yellow, green] 7
[Red, yellow, blue] 7
[Red, Blue] 6 (or [Red, Green]) Report Duplicate  Flag
Google SDE1  0of 0 votes
Answersinput: words [['google', 30], ['gogle', '20'], ...]
 ajay.raj in United States
queries [['go, le'], ...]
output: [30, .....]
The query is suffix and prefix, giving the maximum match. Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersC * R 2D array, there are R, G, B, Y four types of elements, if no vertical and horizontal has three adjacent elements are the same type, then the 2D array is valid
 ajay.raj in United States
Let write a function to determine whether a 2D array is valid.
followup how to generate such a valid 2D array Report Duplicate  Flag
Google Software Engineer  0of 0 votes
AnswersThere are W white beans in the jar, R red beans. Random touch a bean. Touch white beans to eat directly. Touch red beans, put back, touch a bean, whether it is red, eat. Ask the last bean is the probability of white beans.
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
Answers
 ajay.raj in United StatesGive an Node { Node getLeft (); Node getRight (); String toString (); } Give a root node Node root * / \ +  / \ / \ 1 2 3 4 Return (1 + 2) * (34) If (1 + 2) + (3 + 4) does not need to be bracketed Only leaf nodes are numbers followup Give you * + 1234 to return this tree
 Report Duplicate  Flag
Google Software Engineer  1of 1 vote
AnswersGiven a function randBetween (double d1, double d2), return a random double between d1 and d2,
 ajay.raj in United States
returns a random point in a rectangle.
Give a bunch of rectangles, using randBetween to print a random point in the rectangle
follow up: What to do if you call this func many times Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswerThe two arrays [1,2,3,4,5], [2,3,4,5,6] find the first subfix and the second prefix the same longest case, such as the example is [2, 3,4,5]
 ajay.raj in United States
Length of 4.
Followup: how to do twodimensional array, how to optimize. Report Duplicate  Flag
Google SDE1  1of 1 vote
AnswersGiven Two string, ask whether they can become the same after just one swap of two chars in one string.
 ajay.raj in United States
For example:
"abcd", "bacd" Yes, you can swap ab in the first string to make it the same as the second string
"abcd", "adbc" can not
Followup, given Two string, ask whether they can become the same after N swaps of two chars in one string g, assuming that the swap does not overlap.
(str [0] <> str [2] str [2] and str [0] will not be swapped with other locations) Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersAn art museum has the shape of a square and it contains N*N rooms. Some of the rooms are open and they contain art, other rooms are locked. There are guards in some of the open rooms. The museum's administration is afraid of a break in and they would like to evaluate how well the guards are positioned in the open rooms inside the museum. Precisely, they wish to know for each open room what is the distance to the colest guard. This distance is the min number of rooms a guard needs to pass through to reach that room. The guards can only move through the open rooms North, South, East and West and they can't leave the museum.
 ajay.raj in United States
'.' is for open room 'G' is for open room where a guard is '#' is for a locked room Noboday can enter or pass through thesse rooms. Report Duplicate  Flag
Google SDE3  0of 0 votes
AnswerThere is a ball on the nth stairs, and it wants to get to the ground(level 0). There are some sticky stairs, and once the ball lands on the sticky stair, it is stuck and can never move.
 ajay.raj in United States
During odd turns, you can jump down 1, 2, or 4 stairs. During even turns, you can jump down 1, 3, 4 stairs.
Return the number of ways you can get to ground. Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswerYou are in the upper left corner, sitting in a boat, you want to reach to the lower right corner, but the matrix has a certain height at each location (i, j), and the boat can only go through the cell with water in it, looking for the earliest time that the boat can reach from the upper left corner coordinates (0,0) to the lower right coordinates (n1, n1). Each day, water goes up by one height unit
 ajay.raj in United States Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswerChoose a random point from one single rectangle.
 ajay.raj in United States
Choose a random point from multiple rectangles, if there isno overlapping among them.
Choose a random point from multiple rectangles, if there isoverlapping among them. Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersSay you have an array for which the ith element is the price of a given stock on day i, you can buy stock at any day, but can only buy once a day, but if you sell the stock, you must sell all of them at once.
 ajay.raj in United States
Seeking maximum profit
public int maxProfit(int[] prices) { Report Duplicate  Flag
Facebook Java Developer  0of 0 votes
Answersgiven a html file, compare if two html file show the same contents.
 ajay.raj in United States
Eg.
<html> <body> <p> H <i> ello </ i> </ p> <body> </ html> is typed as "Hello \ n" without regard to <i> , "\ n" because of <p>
follow up: what if the string is very long Report Duplicate  Flag
Google Java Developer  0of 0 votes
Answersgiven a binary matrix of 01s, each time you click a point (i, j), the bit of the same row and column are all flipped.
 ajay.raj in United States
check if a matrix can be all 0s after many of this operation. Report Duplicate  Flag
Google SDE1  0of 0 votes
Answerdesign a sweeping robot, there are three functions:
 ajay.raj in United States
move (), which returns boolean value
turn_left (k), which make robot turns left k times.
turn_right (k), which make robot turns right k times.
Design an algorithm to make robot clean up all room. Timecomplexity, linear in term of room space. Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGiven a binary tree, print the path that has the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parentchild connections. The path must contain at least one node and does not need to go through the root. the node val may be negative one
 ajay.raj in United StatesFor example: Given the below binary tree, 1 / \ 2 3 Return 213. 1 / \ 2 3 \ 1 Return 3. public List<Integer> findMaxPath(TreeNode root){ } /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
 Report Duplicate  Flag
Facebook Backend Developer  0of 0 votes
AnswersGiven a graph, each node may have one or more children, updating the value of a child node is not less than the parent node.
 ajay.raj in United States
followup each child node may have one or more parent nodes, Report Duplicate  Flag
Google SDE1  1of 1 vote
AnswersGiven a function that returns 0 and 1 with a probability of fifty percent, use this function to generate a random number between a and b with uniform distribution
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersJudge if two arrays has the same pattern,
 ajay.raj in United States
The definition is the relative relationship between each number and other numbers are the same, such as 132, 354, the first number is less than the second, the first less than the third, the second is greater than the third,
So is the same,
132,352 is not the same, because the first 132 is less than the third, the first 352 is greater than the second,
follow up, the array may concern duplicates Report Duplicate  Flag
Google SDE1  1of 1 vote
AnswersA city bus station information, example, bus No. 1 stops at abcd station, bus No. 2 stops at cefg station. Then ad you only need to take No. 1, thus return 1, ag is 2, because you need to transfer at station c,
 ajay.raj in United States
ask for a minimum bus you need to take to reach to another station. You can design any data structures. Report Duplicate  Flag
Google Software Engineer  0of 0 votes
AnswerThe topic is to design a data structure to store employee relationships.
 ajay.raj in United States
For example, A is B's direct manager, there is an operation is "" set_manager "," A "," B ">.
For example, B is a colleague of C <"set_peer", "B", "C">
At this point, we do this with <query_manager "," A "," B "> and we get True, which means that A is B's manager (either direct or indirect).
This is true if we have <"query_manager", "A", "C">, because C is a coworker for B, so A is also C's manager. That is, there is a transitive relationship between colleagues.
Follow up, such as query <"query_manager", "A", "D"> (D this person has not been initialized), what to do. Conflict how to do
For example, A is a direct manager of B, E is a direct manager of C, which is set_peer (B, C), there will be conflicts, B and C direct manager should be the same person,
E and A are two people, there are contradictions here. Report Duplicate  Flag
Google Java Developer  0of 0 votes
Answergiven a dictionary, output the longest List <String>. The result of a String is the previous String add a character at any position.
 ajay.raj in United States
example: {i, in, ing, sing, sting, string} Report Duplicate  Flag
Google Java Developer  0of 0 votes
AnswersFind a “local minimum” in a binary tree
 ajay.raj in United States
a local min is a node whose value is smaller than that of any other nodes that are connected to it Report Duplicate  Flag
Google Java Developer  0of 0 votes
Answer1. merge intervals with value
 ajay.raj in United States
PD: there are a series of continuous intervals, and each interval has a value. Initially, the ith
interval is (i  1, i  1), merge these intervals and return the result.
Merge Rule:
a. We can only merge the ith interval with i1 th or i + 1 interval. The value of new interval is the
mean of these two original intervals.
b. Define cost as absolute difference of two neighboring intervals,
every time merge two intervals with the smallest cost.
c. If the smallest cost exceeds a threshold t, then stop.
d. There may be multiple valid result, just return one.
for example:
value: 3 7 6 5 1
intervals: (0,0) (1,1) (2,2) (3,3) (4,4)
threshold: t = 2
first iteration:
min cost = 7  6 = 1, notice that 6  5 is also okay.
after merging:
value: 3 6.5 5 1
intervals: (0,0) (1,2) (3,3) (4,4)
second iteration:
min cost = 6.5  5 = 0.5
after merging:
value: 3 5.75 1
intervals: (0,0) (1,3) (4,4)
second iteration:
min cost = 3  5.75 = 2.75 > t = 2, stop
return [(0,0), (1,3), (4,4)] Report Duplicate  Flag
Google Java Developer  1of 1 vote
AnswersGive all n cities the distance between them, and then you have to follow all the cities in the order of small to large index of the city, which means you must visit the cities in ascending order, and now you can choose not to visit k cities (k < n), ask choose not to go to which k cities can make the path shortest? Return the shortest journey.
 ajay.raj in United States
int findShortestPath(int[][] matrix, int k){
} Report Duplicate  Flag
Google SDET  0of 0 votes
AnswersGenerate a random MxN starting board. It cannot have 3 or more pieces in a
 ajay.raj in United States
row (horizontally or vertically) of the same color. K colors. Report Duplicate  Flag
Google SDE1  0of 0 votes
Answersfind the longest substring with at most k repeating characters,
 ajay.raj in United States
to make it more clear, at most k repeating characters means in the substring, the max count(frequency) of one or more chars is k Report Duplicate  Flag
Facebook Java Developer  0of 0 votes
AnswersRobot walked from the upper left to the lower right, can only go down and to the right, the number of each grid is height,
 ajay.raj in United States
If the next cell height is higher than the current, we must pay the difference cost, otherwise no cost,
Find the minimum cost to reach the lower right corner,
Follow up 1, print the minimum cost path; Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersgive a list of cities a to city b the price of air tickets for example
 ajay.raj in United States
a b 100 $
b c 200 $
e f 200 $
...
Now let you from city x to city y, you cannot transfer more than twice between the two city, find the cheap flight from x to y, follow up print out the flight Report Duplicate  Flag
Google Backend Developer  0of 0 votes
AnswersGas station problem, give you a starting point A and End B. An array of oil prices at each gas station index represents the location of each gas station. MPG = V, find the minimum cost of gas from A to B
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  1of 1 vote
Answersgiven a string, and integer k, check if this string contain all the binary string of length k
 ajay.raj in United States
For example, k is 2, then 00,10,01,11.
Followup 1, find a string that can contain all binary string of length k.
Followup 2, find a shortest string that can contain all binary string of length k. Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersExpression evolution
 ajay.raj in United States
expr :: = int  '(' op expr + ')'
op :: = '+'  '*'
Cite a few examples:
"3" > 3
"(+ 1 2)" > 3
"(+ 3 4 5)" > 12
"(+7 (* 8 12) (* 2 (+ 9 4) 7) 3)" > ...
Public int getValue(String s){
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answers
 ajay.raj in United StatesInsert a number into an array of sorted intervals. For example, [1,4], [6,8], after insert 5, return [1,8]. class Interval{ int start; int end; public Interval(int start, int end){ this.start = start; this.end = end; } } class Solution{ public List<Interval> insert(List<Interval> list, int val){ } }
 Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersgive a bunch of job dependency, such as A> B, A > C, B> D, and so on, implement two interfaces.
 ajay.raj in United States
The first one is get_next_stage, which returns jobs in parallel for the next phase. The second is job_done, which tells you which job completed. Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGive a list of the company's Mergers and Acquisitions relationships, for example
 ajay.raj in United States
[
["baidu", "ofo"],
["mobike", "alibaba"],
]
Said baidu acquired ofo, mobike acquired Alibaba.
Seeking the longest of a M & A chain. No cycle Report Duplicate  Flag
Google Backend Developer  0of 0 votes
Answersdetermine whether a number is the sum of two squares, such as 17 = 16 +1
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answers
 ajay.raj in United StatesGive a matrix, for example 1 0 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 1 0 1 Find if there is a rectangle in the matrix, all four corners are 1 For the example, there is only one rectangle, that is 1 0 1 0 1 0 1 0 1
 Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersclass DirectedGraphNode {
 ajay.raj in United States
int label;
List<DirectedGraphNode> neighbors;
DirectedGraphNode(int x) {
label = x;
neighbors = new ArrayList<>();
}
}
check if there is a cycle in a directed graph, if there is a cycle, remove all the cycles Report Duplicate  Flag
Facebook SDE1  1of 1 vote
AnswersYou are given a binary tree and a function shouldBeErased(node to check whether a node should be erased. Erase all nodes that should be erased in the binary tree and return the resulting forest in the form of an array of every root node.
 ajay.raj in United States
Follow up:
What if this is a Binary Search Tree? (In this case you are given a list of nodes that should be erased instead of the function.) Does it make the problem simpler or more complicated or just the same? Report Duplicate  Flag
Google SDE1  0of 0 votes
Answersgiven a string and a segmentation length k
 ajay.raj in United States
For example:
"This is a good day" k = 10
Cut into:
"This (1/4)"
"is a (2/4)"
"good (3/4)"
"day (4/4)"
Each line followed by a suffix in the form of (i/n) has 10 chars including space (except for the last line), return the minimum cut required, for the example, just return 4. Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answerstrie search, Search Return all words that match the wildcard *
 ajay.raj in United States
such as
add ("car")
add ("caw")
add ("cauw")
search ("c*w") returns "caw" and "cauw". Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersgiven a target node in a directed graph, find the shortest cycle including this node, return the whole path.
 ajay.raj in United States Report Duplicate  Flag
Facebook Intern  0of 0 votes
AnswersThere are n bus lines, known bus stops by bus, the bus is bidirection, ask from station A to station B at least a few transfers.
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
Answers
 ajay.raj in United Statesgiven a binary array, you can flip 0 > 1 or 1 > 0 to make all the 1 are in the left part and all the 0 to the right part, return the minimun flip required example 1 1011000 > 1111000 only need one flip 0 > 1 example 2 00001 > 10000 require 2 flips public int findMiniFlip(int[] nums) { } }
 Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersthe longest unique value path in a graph
 ajay.raj in United States
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public int findLongestUniqueValuePath(List<UndirectedGraphNode> node) {
}
} Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGiven a string s, break s such that every substring of the partition can be found in the dictionary.
 ajay.raj in United States
Return the minimum break needed.
Example
Given a String CatMat
Given a dictionary ["Cat", "Mat", "Ca", "tM", "at", "C", "Dog", "og", "Do"]
return 1
we can break the sentences in three ways, as follows:
CatMat = Cat Mat break 1
CatMat = Ca tM at break 2
CatMat = C at Mat break 2
but the first way has the minimum break, thus return 1
public int wordBreak(String s, Set<String> dict) {
// Write your code here
} Report Duplicate  Flag
Facebook SDET  0of 0 votes
AnswersGiven a 2d grid map of '1's (land) and '0's (water), find the perimeter of each island. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersTo determine if two graphs have isomorphism or not
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGive an array A, find the (i, j) pairs that satisfy the condition.
 ajay.raj in United States
Condition 1: A [j] = A [i] + 1, Condition 2: j  i is as large as possible
Followup condition 1 is changed to A [j]> A [i] Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven an array of length n + 1, containing elements 1 through n and a space,
 ajay.raj in United States
Requires the use of a given swap (index i, index j) function to sort the array,
You can only swap the gap and a number, in the end, put the gap at the end Report Duplicate  Flag
Google SDE1  0of 0 votes
Answersfind a shortest string to cover all of a list of string,
 ajay.raj in United States
For example, [aab, aabb, bc], should return aabbc,
because aab, aabb, bc are all the substring of aabbc Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersgiven 2 list of interval representing users online offline timestamp e.g (already sorted), find all intervals that both of users are online.
 ajay.raj in United States
e.g A= [(3, 5), (7, 11)] B=[(2, 4), (9, 10)] > [(3, 4), (9, 10)]. Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswerDesign a SparseVector class that implements
 ajay.raj in United States
Vector interface, which contains 4 methods: get(int index),
increment(int index, int delta), numNonZeros(), and dotProduct(Vector other) Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswerGive a vote list = [(a, 100), (b, 150), (a, 200)] # (name, timestamp) and time T
 ajay.raj in United States
Find the highest number of votes (or anyone with the highest number of votes) at T
ex: T = 100 > a, T = 150 > a or b, T = 200 > a
followup1, give one more input K, find Top K votes at T
followup2, the same vote list, K, but given the Top K votes list, find the time T. Report Duplicate  Flag
Google SDET  0of 0 votes
AnswersGiven an array of integers and k, find the difference between the number of the strictly increasing number of subarrays (of size more than one) and the number of the strictly decreasing subarray in the window of size k. your method should be time and space efficent
 ajay.raj in United States
example
int[] nums = {188930, 194123, 201345, 154243, 154243};
int k = 3;
Output
3, 0, 1
Explanation
For the first window of [188930, 194123, 201345], there are 3 increasing subranges ([188930, 194123, 201345], [188930, 194123], and [194123, 201345]) and 0 decreasing, so the answer is 3. For the second window of [194123, 201345, 154243], there is 1 increasing subrange and 1 decreasing, so the answer is 0. For the third window of [201345, 154243, 154243], there is 1 decreasing subrange and 0 increasing, so the answer is 1.
public int[] getdiff(int[] nums, int l){
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answers
 ajay.raj in United Statesgive an enum, where each element has a parentchildren relationship, and children's expression is the value of parent append an index, such as enum vehicle { car = 1 toyota = 11 camry = 111 corolla = 112 honda = 12 truck = 2 GMC = 21 } Ask a value, return to his parent, such as GMC = 21, return to the truck
 Report Duplicate  Flag
Google SDE1  1of 1 vote
AnswersGiven a list points on a 2d plane, find
 ajay.raj in United States
largest rectangular area that can be formed
for the rectangle only considers those parallel to x and y Report Duplicate  Flag
Google SDE1  0of 0 votes
Answers
 ajay.raj in United StatesThere is an unordered interval stream, write a method, returns the total length that all intervals cover by now class Interval{ int start; int end; } public List<Integer> countCoverLength(Iterator<Interval> stream){ }
 Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answers‘.’Matches any single character,' * 'Matches any sequence of characters (including the empty sequence).
 ajay.raj in United States
There are two input, one is string pattern, and the other is dictionary like dict = ["cat", "cats", "and", "sand", "dog"].
return a boolean: whether to find a dictionary in the pattern match the word
eg: dict = ["cat", "cats", "and", "sand", "dog"].
pattern = "* t", > true (can match cat)
pattern = ".a *" > true (can match cat, cats, can also match sand, because * can also express empty sequence) Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersHow would you store and retrieve values in Memcache if the values are larger than the individual value size allowed by Memcache?
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  2of 2 votes
Answersnode {
 ajay.raj in United States
node * left, * right;
}
Given a list of node to determine whether the node in the list can form a valid binary tree. several points of judgment
1. need to ensure that all left, right pointer point to the node inside list
2. no cycle
3. All node must be connected
Boolean isValidTree(List<Node> list){} Report Duplicate  Flag
Facebook Software Developer  1of 1 vote
AnswersGiven a matrix of N * M, given the coordinates (x, y) present in a matrix,
 ajay.raj in United States
Find the number of paths that can reach (0, 0) from the (x, y) points with k steps (requires exactly k, k> = 0)
From each point you can go up, down, left and right in four directions.
For example, the following matrix:

0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
(x, y) = (1, 1), k = 2, the output is 2 Report Duplicate  Flag
Facebook Software Developer  0of 0 votes
AnswersFind all words [AZ] in a dictionary (about 1M words) that are made of a subset (in any order) of the chars in the input parameter [AZ].
 ajay.raj in United States
ex: input "ACRAT" (10 to 20 chars, up to 30 worst case)
matching words: "A", "CAR", "ACA", "ART", "RAC".
nonmatching words: "BAR", "AAA"
follow up : the input is a list of words. Return a list of words that each
list is formed by exactly the characters in the input list.
For example: two lists {“DEBIT”, “CARD”} and{“BAD”, “CREDIT”}
are formed by the same exact group of characters. Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven a string separated by a space like "123456 abc+efg" determine
 ajay.raj in United States
the solution by mapping integers to letters like a:1, b:2, c:3, d:4, e:5, f:6.
The only operations allowed were + or . So the calculated solution
that made the tests pass was 123+456 = 579. Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersHow many subsets of a given array sum to zero?
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven numbers 1 through 52, take 5 unique numbers and determine
 ajay.raj in United States
if the number 42 can be made using any combination of addition (+),
subtraction (), multiplication (*), and division (/) on those 5 numbers Report Duplicate  Flag
Facebook SDE1  1of 1 vote
Answers/* Intersection of two sorted interval lists, A=[(1,2), (5,7)..]
B=[(2,6)...] return [(5,6)..] */
 ajay.raj in United Statesimport java.util.*; class Interval{ int start; int end; public Interval(int start, int end){ this.start = start; this.end = end; } } class Solution { public List<Interval> Intersection(Interval[] i1, Interval[] i2) {}
 Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answers* Given a string on length N. You can swap only the adjacent elements
 ajay.raj in United States
and each element can be swapped atmost once.
Find the no of permutations of the string that can be generated after
performing the swaps as mentioned.
Ex –
string – “12345”
Ans = 8
Explanations (All the permutations)
12345
21345
13245
12435
12354
21435
13254
21354 Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven an array of n positive integers, find the number of subarrays
 ajay.raj in United States
such that product of the elements of those subarrays are less than k.
For eg. Arr= {2, 3, 6} k=10
No of such subarrays= 4 Report Duplicate  Flag
Facebook SDE1  1of 1 vote
AnswersPrint the levels of a binary tree in reverse order using stack and recursion
Given a binary tree, return the bottomup level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree 3 / \ 9 20 / \ 15 7 return its bottomup level order traversal as: [ [15,7], [9,20], [3] ]
public List<List<Integer>> levelOrderBottom(TreeNode root) {
 ajay.raj in United States
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersgiven an array, find whether there exists 3 elements a,b,c in it such that a+b=c using efficient method.
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersYou are provided a BST, which is corrupted. One of the nodes in it has 2 parents.
 ajay.raj in United States
Let’s say those are parent 1 and parent 2. It is ensured that none
of these parents will be the ancestor of the other. Identify the node,
and remove the link of the wrong parent. Report Duplicate  Flag
Facebook SDE1  1of 1 vote
Answersgiven an array of strings and characters, make the largest string possible.
 ajay.raj in United States
The resultant string should be a combination of the strings given in the array.
The given array
of characters may contain repeated elements.
Example – Given char array – {a,a,b,c,d,d,e,c} and given strings
– {abba, aabc, de, cde} the
ans is aabccde Report Duplicate  Flag
Facebook SDET  1of 1 vote
AnswersGiven an adjacency matrix of a directed graph, find the number of cycles in the graph
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answers
 ajay.raj in United StatesGiven an array of n * m matrix, and a moving matrix window (size k * k), move the window from top left to bottom right at each iteration, find the median number inside the window at each moving Can you do it better than brutal force method? void getMedian(int[][] matrix, int k){ print median } For matrix [ [1, 5, 3], [3, 2, 1], [4, 1, 9], ] The moving window size k = 2. At first the window is at the start of the array like this [ [1, 5, 3], [3, 2, 1], [4, 1, 9], ] ,get the median (2 + 3) / 2 = 2.5; then the window move one step forward. [ [1, 5, 3], [3, 2, 1], [4, 1, 9], ] ,get the median (2 + 3) / 2 = 2.5 then the window move one step forward again. [ [1, 5, 3], [3, 2, 1], [4, 1, 9], ] ,get the median (2 + 3) / 2 = 2.5 then the window move one step forward again. [ [1, 5, 3], [3, 2, 1], [4, 1, 9], ] ,get the median (1 + 2) / 2 = 1.5
 Report Duplicate  Flag
Facebook SDE1  3of 3 votes
AnswersWe are planning an orienteering game.
 ajay.raj in United States
The aim of this game is to arrive at the goal (G) from the start (S) with the shortest distance.
However, the players have to pass all the checkpoints (@) on the map.
An orienteering map is to be given in the following format.
########
#@....G#
##.##@##
#..@..S#
#@.....#
########
In this problem, an orienteering map is to be given.
Calculate the minimum distance from the start to the goal with passing all the checkpoints.
Specification
* A map consists of 5 characters as following.
You can assume that the map does not contain any invalid characters and
the map has exactly one start symbol 'S' and exactly one goal symbol 'G'.
* 'S' means the orienteering start.
* 'G' means the orienteering goal.
* '@' means an orienteering checkpoint.
* '.' means an openedblock that players can pass.
* '#' means a closedblock that players cannot pass.
* It is allowed to move only by one step vertically or horizontally (up, down, left, or right) to the
next block.
Other types of movements, such as moving diagonally (left up, right up, left down and right down)
and skipping one or more blocks, are NOT permitted.
* You MUST NOT get out of the map.
* Distance is to be defined as the number of movements to the different blocks.
* You CAN pass openedblocks, checkpoints, the start, and the goal more than once if necessary.
* You can assume that parameters satisfy following conditions.
* 1 <= width <= 100
* 1 <= height <= 100
* The maximum number of checkpoints is 18. Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersconvert prefix to postfix expression
 ajay.raj in United States
public String convert2postfix(String prefix){
} Report Duplicate  Flag
Facebook SDE1  1of 1 vote
AnswersGiven an array of integers where each element points to the index of the next element how would you detect if there is a cycle in this array
 ajay.raj in United States
can you do it without extra space Report Duplicate  Flag
Facebook SDE1  2of 2 votes
AnswersThere is a maze of size m*n. You are sitting at (0,0). Another person is sitting in another cell. There are some cheeses placed in different cells with a cell value of 2. Some cells are blocked with a value of 1, thus you cannot pass it, while some cells are filled with 0, thus you can pass it.
 ajay.raj in United States
You can move to left, right, up, down at each step. You have to collect all the pieces of cheese and then reach to Another Person cell. You need to return the minimum no. of steps required to do so.
Public int getShortest(int[][] maze, int[] anotherPersonCell){
} Report Duplicate  Flag
Facebook SDE1  1of 1 vote
AnswersWe start with a list of Integers. We can remove a group of integers from the list if the all but one equals the remaining number. This removal operation can be performed in the remaining number of list until no more operations can be performed.
 ajay.raj in United States
Write a function which can accept an array of integers, and return the minimal number of remaining integers from performing this operation.
Example [1, 3, 5, 6] > remove 1, 5, 6 , because 1 + 5 = 6, thus only [3] left, so return 1
[48, 20, 1, 3, 4, 6, 9, 24] > remove 3, 6, 9 , because 3 + 6 = 9, and remove 4, 20, 24, 48, because 4 + 20 + 24 + 48, thus only [1] left, so return 1
int left(int[] nums){
} Report Duplicate  Flag
Facebook Software Developer  0of 0 votes
AnswersThe numbers on a telephone keypad are arranged thus:
1 2 3 4 5 6 7 8 9 0
Starting from any digit, and choosing successive digits as a knight moves in chess, determine how many different paths can be formed of length n. There is no need to make a list of the paths, only to count them.
 ajay.raj in United States
A knight moves two steps either horizontally or vertically followed by one step in the perpendicular direction; thus, from the digit 1 on the keypad a knight can move to digits 6 or 8, and from the digit 4 on the keypad a knight can move to digits 3, 9 or 0. A path may visit the same digit more than once.
Your task is to write a function that determines the number of paths of length n that a knight can trace on a keyboard starting from any digit .
public int findNumberOfPaths(int digit, int step){ Report Duplicate  Flag
Facebook Software Engineer  2of 2 votes
AnswersIn Docker, building an image has dependencies. An image can only be built once
 ajay.raj in United States
its dependency is built (If the dependency is from outside, then the image can
be built immediately).
Sometimes, engineers make mistakes by forming a cycle dependency of local images.
In this case, ignore the cycle and all the images depending on this cycle.
Input is vector of pair of images (image, its dependency).
Output the order of images to be built in order.
##Example:
```
Example 1:
{{"master", "ubuntu"}, {"numpy", "master"}, {"tensorflow", "numpy"}}
Output: master, numpy, tensorflow
Example 2:
{{"python", "numpy"}, {"numpy", "python"}, {"tensorflow", "ubuntu"}}
Output: tensorflow
Example 3:
{{"b", "c"}, {"c", "d"}, {"a", "b"}, {"d", "e"}, {"e","c"}, {"f", "g"}}
Ouput: f Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersThere are n servers, reboot time is S0, S1..Sn1
 ajay.raj in United States
There are m tasks, the completion of the time required are T0, T1… Tm1
How to assign tasks to each server makes the total time the shortest Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersInput: expression_tree  sequence_of_operations
 ajay.raj in United States
The input is a single line of text with a expression tree and a sequence of operations separated by  character and ended by a \n newline character. Spaces are allowed in the input but should be ignored.
The expression tree is a sequence of 1character variables AZ and with sub expression trees formed by parenthesis (expression_tree). Examples: AB, A(B C D), (AB)C((DE)F)
The sequence of operations is a string of with characters R (reverse) or S (simplify)
Reverse means reverse the order of everything in expression tree. Applying reverse twice in a row cancels out. Example: (AB)C((DE)F)  R should print (F(ED))C(BA)
Simplify means remove the parentheses around the very first element in the expression tree and each of its subexpression trees. Applying S multiple times should have same result as applying S once. Example: (AB)C((DE)F)  S should print ABC(DEF)
String process(String input){
} Report Duplicate  Flag
Twitter SDE1  0of 0 votes
AnswersConvert Json string to Map
 ajay.raj in United States
public Map jsonToMap(String t) {
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersWhat if server is slow, how to solve
 ajay.raj in United States
What if one server is down Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven a 2D matrix of 0's and 1's, where the 1's make up a rectangle, find the coordinates of the topleft corner of the rectangle and the rectangle's width and height.
 ajay.raj in United States Report Duplicate  Flag
Facebook Jr. Software Engineer  1of 1 vote
AnswersArray has N integers，range[0...N1]。Set S[k], 0 <= K < N as S[K] = {A[K], A[A[K]], A[A[A[K]]],....},
 ajay.raj in United States
write a function returns the size of the largest set S[K] for this array. return 0 if empty.
ex:
A = [5, 4, 0, 3, 1, 6, 2]
return 4 because S[2] equals {0, 5, 6, 2} 4 elements Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven an array of integers and a target number, determine if an arithmetic expression using these integers can be evaluated to the target number, you are allowed to use '+', '', '*', '/'. Followup: when evaluating the expression, take operand precedence into account,
 ajay.raj in United States
public boolean getTarget(int[] nums, int target){
}
exponentia is ok Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersfind the Closest leaf to a given node in Binary Tree
 ajay.raj in United States
can you do it in o(n) time
public TreeNode findCloestLeafNode(TreeNode root, TreeNode target){}
no parent pointer Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answervalidate IP in string format and return the uint32 format
 ajay.raj in United States
‘1.2.3.4’ > 0x01020304 Report Duplicate  Flag
Facebook SDE1  1of 1 vote
AnswersGiven a nnery tree and its deep copy, a node in the original tree, return the corresponding node in the copy
 ajay.raj in United States
public TreeNode getCopyNode(TreeNode root, TreeNode copy, TreeNode node) Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answerwrite bash code to determine if the first number in the string is greater than 1000
 ajay.raj in United States
STR="count  43952 (1 rows)" Report Duplicate  Flag
Amazon Backend Developer  0of 0 votes
AnswersWrite the code to find the median of an unsorted array in average linear time.
 ajay.raj in United States
followup the array is distributed across many machines. Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswerWrite a function to split a SQL query into individual statements.
 ajay.raj in United States
give you a String which contains a separate Query with a semicolon ";" return all valid queries
Such as
"select name from courseinfo ;; select * from db1 where home = 'usa' ;"
The main thing to consider is that some special cases such as the escape symbol and the quotation marks inside the semicolon
public List<String> getQuery(String queries){
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersgiven a list of numbers, put with +  * / any two number, find the maximum value you can get.
 ajay.raj in United States
int getMaxNumber(int[] nums){
} Report Duplicate  Flag
Facebook Software Engineer  0of 0 votes
AnswersGiven a group of movies and their start time, assuming that are 1 hour long,
 ajay.raj in United States
Returns a movie schedule (no time conflict).
enter:
Movie ("Shining", [14, 15, 16])
Movie ("kill bill", [14, 15])
Movie ("Pulp fiction", [14, 15])
One possible result is shining 16, kill bill 15, pulp fiction 14
public void schedule (HashMap <String, List <Integer >> map) {
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersfriend circle. Given a streaming pairs representing friend relationship
 ajay.raj in United States
(1, 2) means 1 and 2 are friends, (1, 3) means 1 and 3 are friends
Return all its friends.
List<Integer> getFriends (Iterator<List<Integer>> relations, int id){
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersgiven a matrix and a target, return if there is a path who’s sum is == target
 ajay.raj in United States
Input: matrix, integer output: true or false; Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answerspermute the String including case change
 ajay.raj in United States
"abc".
For example:
abc
ABC
Abc
aBc
abC
ABc
abC
AbC Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersimplemnt JSON.stringify()
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  1of 1 vote
Answersgiven a string of number, you can add a + or * sign between any two numbers, find the maximum value you can get
 ajay.raj in United States
ex. s = "89" > 8 * 9 = 72
int maxNumber(String s){} Report Duplicate  Flag
Facebook Software Engineer  0of 0 votes
AnswersGive you an unsorted integer iterator
 ajay.raj in United States
and a percentage that is expressed in double (for example, 0.4 for 40%),
and find the number of the sorted array at the percentage position.
Example: Enter [1 3 2 5 4 6 7 9 8 10], and 0.6, you will return 6
public int findNumber(Iterator<Integer> nums, double percent){
} Report Duplicate  Flag
Facebook Software Engineer  0of 0 votes
Answerscan you use union find to Detect Cycle in a Directed Graph? why or why not
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersShell command, there is a log file, you want all the "error" inside the line to find out into another file inside,
 ajay.raj in United States
What instruction, Report Duplicate  Flag
Amazon SDE1  0of 0 votes
Answerhow to design github
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersReturn the most popular 10 words in the past 24 hours for twitter
 ajay.raj in United States
Follow up in order to reduce the size of each log, do not write timestamp, how to get the same answer, Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven a Calendar class (there are three fields, year, month, day) and a number of N,
 ajay.raj in United States
Implement a function that returns the calendar after N days,
For example, if the input is {2017, 3,20} and 12, then the return is {2017,4, 1} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersimplement a Fibonacci iterator
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  1of 1 vote
AnswersNow we have one server, one database, what if response time is slow?
 ajay.raj in United States
How to optimize? Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven an integer n, count the total number of digit 3 appearing in all nonnegative integers less than or equal to n.
 ajay.raj in United States
(E.x: given 30, return 4 {3,13, 23, 30}) Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersprime factors. given a number return the prime factor multiplication.
 ajay.raj in United States
eg. 90 = 2 * 3 * 3 * 5. Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersRemove any number containing 9 like 9, 19, 29, ... 91, 92, ... 99, 109...
 ajay.raj in United States
Write a function that returns the nth number. E.g. newNumber(1) = 1
newNumber(8) = 8, newNumber(9) = 10 Report Duplicate  Flag
Facebook SDE1  2of 2 votes
AnswersGiven a n*m size 2D array with integers from 1 to n*m  1 in it.
 ajay.raj in United States
Integers are not sorted. The last position of the matrix stays a movable block.
For each time, you can swap the movable block with any adjacent number.
And eventually you will have the integers sorted and the movable block returned
to its starting position. Think about an approach to print the path.
(You can assume it always have at least a solution) Report Duplicate  Flag
Facebook Software Engineer  0of 0 votes
AnswersHow to get the repeating decimal pattern of a division? (e.g 1/3, 1/6)
 ajay.raj in United States Report Duplicate  Flag
Facebook Software Engineer  1of 1 vote
AnswersGiven a preorder traversal of a BST, print out the inorder transversal of the BST
 ajay.raj in United States
public void printInorder(int[] nums){} Report Duplicate  Flag
Facebook Software Engineer  0of 0 votes
Answers/* Find all subsets of size k in an array that sum up to target
 ajay.raj in United States
the array may contains negative number */
class Solution {
public List<List<Integer>> combinationSum(int[] nums, int target, int k) {
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersA bot is an id that visit the site m times in the last n seconds,
given a list of logs with id and time sorted by time, return all the bots's id
 ajay.raj in United Statesclass Log{ String id; int time; } public HashSet<String> getBots(Log[] logs, int m, int n){ }
 Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answershow to implement a Wish List like this one
 ajay.raj in United States
https://www.amazon.com/hz/wishlist/intro Report Duplicate  Flag
Amazon SDE1  0of 0 votes
Answersdownload all urls from 1000 hosts. Imagine all the urls are graph.
 ajay.raj in United States
Requirement: Each host has bad internet connection among each other, Has to download url exacly once. Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswerGive you a robot and a room where you do not know where the robot is in the room and you do not know the size of the room, you have a remote control that allows the robot to walk around four directions. Here you give a move method: boolean move (int direction), direction: 0,1,2,3 that four directions. If it can move in that direction, return true, and if it cannot move in that direction, return false. Ask you determine how big this room is. the shape of the room can be any shape, so you cannot assume it is rectangle or square.
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven n1, n2 is the number after removing one digit from n1. Example, n1 = 123, then n2 can be 12, 13 or 23.
 ajay.raj in United States
If we know the sum of n1 + n2, and find the possible values of n1 and n2.
public List<List<Integer>> getNumber(int sum){
} Report Duplicate  Flag
Facebook SDE1  1of 1 vote
AnswersDesign copyonwrite string class
 ajay.raj in United States
e.g. stringclass s("abc");
stringclass s1 = s; // no copy
s = "bcd"; // copy Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven an ODD number, print diamond pattern of stars recursively.
n = 5, Diamond shape is as follows: * *** ***** *** *
void print(int n){
 ajay.raj in United States
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answers/From the input array, output a subset array with numbers part of a Fibonacci series.
 ajay.raj in United States
// input: [4,2,8,5,20,1,40,13,23]
// output: [2,5,1,8,13]
public static List<Integer> getFibNumbers(int[] nums){} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersCan multiple threads improve the time complexity to merge k sorted arrays? If so, how?
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1 Arrays  0of 0 votes
AnswersGives an array of unsorted int (may have negative number),
 ajay.raj in United States
rearrange the array such that the
num at the odd index is greater than the num at the even index.
example
giving 5, 2, 3, 4, 1, one of the expected result is 1,4,2,5,3,
please solve it in o(n) time, where n is the length of the array
public void rearrange(int[] nums){
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answers
 ajay.raj in United StatesGiven a string, find all possible combinations of the upper and lower case of each Alphabet char, keep the none Alphabet char as it is. example1 s = "ab", return: "Ab", "ab", "aB", "AB" example2 s = "a1b", return: "A1b", "a1b", "a1B", "A1B" public List<String> getPermutation(String s){ }
 Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersFor a given array, find the subarray (containing at least k number) which has the largest sum.
 ajay.raj in United States
Example:
// [4, 2, 1, 3], k = 2, return 1, and the subarray is [2, 1]
// [1, 1, 1, 1, 1, 1], k = 3, return 6, and the subarray is [1, 1, 1, 1, 1, 1]
try to do it in O(n) time
Followup, if input is stream, how to solve it
public int maxSubArray(int[] nums, int k) {} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answersfind maximum contiguous subarray sum with size (the number of the element in the subarray) <= k
 ajay.raj in United States
a brute force method is very simple, can you do it better?
public int maxSum(int[] nums, int k){
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answers// Read4K  Given a function which reads from a file or
 ajay.raj in United States
// network stream up to 4k at a time, give a function which
// which can satisfy requests for arbitrary amounts of data
private int read4K(char[] buf) {
// GIVEN
}
// IMPLEMENT:
public int read(char[] buf, int toRead) { }
Due to network latency, if the read4K method return a value < 4k, it does not necessarily mean that we reach the End of File (EOF), in this case, you should continue to read the file until you reach toRead or EOF. Report Duplicate  Flag
Facebook SDE1  1of 1 vote
Answerhow to keep track of the sum in a sliding window for the data that are on disk
 ajay.raj in United States
rather than memory Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersInsert a node in a complete binary tree efficiently.
it is not BST, it is just a regular binary tree
public TreeNode insert(TreeNode root, int val){
}
this my solution using bfs (O(n) time), is there any more efficient method?
 ajay.raj in United Statesimport java.util.*; class TreeNode{ int val; TreeNode left; TreeNode right; public TreeNode(int val){ this.val = val; } } class Solution{ public TreeNode insertCompleteTree(TreeNode root, int val){ if(root == null){ return new TreeNode(val); } Queue<TreeNode> q = new LinkedList<>(); q.add(root); while(!q.isEmpty()){ int size = q.size(); for(int i = 0; i < size; i++){ TreeNode cur = q.remove(); if(cur.left == null){ cur.left = new TreeNode(val); return root; }else{ q.add(cur.left); } if(cur.right == null){ cur.right = new TreeNode(val); return root; }else{ q.add(cur.right); } } } return null; } public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> res = new ArrayList<>(); if(root == null){ return res; } Queue<TreeNode> q = new LinkedList<>(); q.add(root); while(!q.isEmpty()){ int size = q.size(); List<Integer> list = new ArrayList<>(); for(int i = 0; i < size; i++){ TreeNode cur = q.remove(); list.add(cur.val); if(cur.left != null){ q.add(cur.left); } if(cur.right != null){ q.add(cur.right); } } res.add(list); } return res; } public static void main(String[] args){ Solution s = new Solution(); TreeNode root = null; int[] nums = {1, 2, 3, 4, 5, 6, 7}; for(int num : nums){ root = s.insertCompleteTree(root, num); System.out.println(s.levelOrder(root)); } } }
 Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersA table has some number of balls at various positions on a line segment.
 ajay.raj in United States
All are moving with same speed in one or the other direction.
Wherever a collision occurs they change direction.
A ball falls from the edges of the table.
Find the time when all balls fall of the table
given initial position of each ball and speeds Report Duplicate  Flag
Google SDE1  0of 0 votes
Answersgiven a graph: example > A company holds 10% of B company’s share,
 ajay.raj in United States
B company holds 5% of C company’s share, A company holds 2% of C company’s share,
what percent of C company’s share does A company hold? Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answers
 ajay.raj in United States// Design and implement key value system // // string > string // Insert a keyvalue pair or modify a value void put(string key, string value); // Delete a keyvalue pair void delete(string key); // Gets a value given a snapshot string get(string key, Snapshot snap); // Take a snapshot Snapshot takeSnapshot(); // Delete a snapshot void deleteSnapshot(Snapshot snap); // put(k1,v1) // put(k2,v2) // put(k3,v3) // takeSnapshot > snap1 { k1 > v1, k2 > v2, k3 > v3 } // get(k1,snap1) > v1 // put(k1,v4) // delete(k3) // takeSnapshot > snap2 { k1 > v4, k2 > v2 } // get(k1,snap2) > v4 // get(k1,snap1) > v1 // get(k3,snap2) > XX // deleteSnapshot(snap1) // get(k1,snap1) > XX // Space efficient is more important than time efficient, thus please use as small space as possible.
 Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersWhat is the cost / complexity of a String.indexof() function call in java?
 ajay.raj in United States Report Duplicate  Flag
Amazon SDE1  0of 0 votes
AnswersGiven a task sequence tasks such as ABBABBC, and an integer k, which is the cool down time between two same tasks. Assume the execution for each individual task is 1 unit.
 ajay.raj in United States
rearrange the task sequence such that the execution time is minimal.
Example:
S = AAABBBCCC, K = 3
Result: ABCABCABC (all 'A's are 3 distance apart, similarly with B's and C's), thus return 9
S = AAABC, K=2
Result: ABCA_ _A, thus return 7
S = AAADBBCC, K = 2:
Result: ABCABCDA, thus return 8
public int rearrangeTasks(String tasks, int cooldown){
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven an array of n elements which contains elements from 0 to n1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space.
 ajay.raj in United States
Try to do it in one pass
example
[4, 2, 0, 5, 2, 0, 1] return: 0, 2
[1, 2, 3, 0, 0, 1, 3, 6, 6,6] return 0, 1, 3, 6
public List<Integer> findRepeat(int nums[]){
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersHow to check the validity of a 4 digit credit card expiration date (mm/yy)
 ajay.raj in United States
that still works 100 years from now.
public boolean isValid(String s){
} Report Duplicate  Flag
Amazon SDE1  0of 0 votes
Answerswhat is the time complexity for java.util.Random.nextInt()
 ajay.raj in United States Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
Answersconvert a ternary expression into a Binary tree structure. a?b:c a / \ b c a?b?c:d:e a / \ b e / \ c d class TreeNode{ char val; TreeNode left; TreeNode right; public TreeNode(char val){ this.val = val; } } public TreeNode build(String s){}
try to do it in o(n) time complexity, n is the size of the string
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersSuppose you have a 2D grid. Each point is either land or water. There is also a start point and a goal. There are also keys that open up doors. Each key corresponds to one door. Implement a function that returns the shortest path from the start to the goal using land tiles, keys and open doors. Data Representation The board will be passed as an array of chars. A board can have the following tiles. 0 = Water 1 = Land 2 = Start 3 = Goal uppercase = door lowercase = key Example Maps (keys at each step are not required) `No doors` char[][] board1 = {{'0', '2', '1', '1', '1'}, {'0', '1', '0', '0', '1'}, {'0', '1', '0', '0', '3'}, {'0', '1', '0', '0', '1'}, {'0', '1', '1', '1', '1'}}; path : [0,1]>[0,2]>[0,3]>[0,4]>[1,4]>[2,4] `One door` char[][] board2 = {{'0', '2', '1', '1', '1'}, {'0', '1', 'a', '0', 'A'}, {'0', '1', '0', '0', '3'}, {'0', '1', '0', '0', '1'}, {'0', '1', '1', '1', '1'}}; path : [0,1]>[0,2]>[1,2]>[0,2]>[0,3]>[0,4]>[1,4]>[2,4]
public List<int[]> solve(char[][] board) {
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGroup a list of words so that the same group of words have a common substring, and this common substring is also in the word lists,
 ajay.raj in United States
example
[cow "," cold "," an "," co "], return [[" can "," an "], [" cow "," cold "," co "]]
["can", "cow", "cold"], return [["can"], ["cow"], ["cold"]]
["c", "ca", "can"], return [["c", "ca", "can"]]
public List<List<String>> groupWords(String[] s) Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersEnter a two digit number, find the year closest to this year.
 ajay.raj in United States
Example input 99, return 1999;
Input 15, return 2015.
public int getClosestYear(int input){
} Report Duplicate  Flag
Facebook SDE1  2of 4 votes
Answersgenerate random number which differs from the number generated last time in the range of [min, max)
 ajay.raj in United States
what is the best way to do it?
public int getNumber(int min, int max){
} Report Duplicate  Flag
Facebook SDE1  1of 1 vote
AnswersGiven a undirected graph with each node representing a char and a word,
check if the word can be formed by any path of the graph
example
graph:
adogact
word : dog, return true;
word: cat, return false;
The same letter may not be used more than once.
 ajay.raj in United Statesclass Node { char label; List<Node> neighbors; Node(char x) { label = x; neighbors = new ArrayList<>(); } } class Solution { public boolean exist(List<Node> nodes, String word) { } }
 Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven a Binary tree (Not binary Search Tree ), find the inorder successor of a node.
 ajay.raj in United Statesclass TreeNode{ TreeNode left; TreeNode right; int val; public TreeNode(int val){ this.val = val; } } public TreeNode inOrderSuccessor(TreeNode root, TreeNode n) {
 Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven a positive integer n, find the no of integers less than equal to n, whose binary representation doesn't contain consecutive 1s.
 ajay.raj in United States
eg:
I/P : 4
O/P: 4 (0,1,2,4 Valid)
public int count(int n){
} Report Duplicate  Flag
Facebook SDE1  1of 1 vote
AnswersGiven m 0 and n 1, count the total number of permutations where two 1 cannot be adjacent
 ajay.raj in United States
public int count(int m, int n){
} Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersGiven a binary tree, return all the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
 ajay.raj in United States/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ 1 / \ 2 3 / \ 4 5 Return [4,2,1,3] and [5,2,1,3]. Public List<List<Integer>> getLongestPath(TreeNode root) { }
 Report Duplicate  Flag
Google SDE1  1of 1 vote
AnswersGenerate a random 4digit even number : the adjacent 2 digits must be different.
 ajay.raj in United States
public int getNumber(){
} Report Duplicate  Flag
Google Software Engineer  1of 1 vote
Answerswrite a function that randomly return a random Fibonacci number in range [min, max)
 ajay.raj in United States
public int getRandom (int min, int max){} Report Duplicate  Flag
Google SDE1  0of 0 votes
Answerswrite a function that randomly return a random prime number in range [min, max)
 ajay.raj in United States
public int getRandom (int min, int max){} Report Duplicate  Flag
Google SDE1  0of 0 votes
Answershow does java implement priority queue?
 ajay.raj in United States
i answered min heap, the interviewer seemed it was not right Report Duplicate  Flag
Amazon SDE1  0of 0 votes
Answer
 ajay.raj in United Statesclass Log{ String fun_name; String enterOrExit;// enter or exit int time; public Log(String fun_name, String enterOrExit, int time){ this. fun_name = fun_name; this. enterOrExit = enterOrExit; this.time = time; } } public void printInclusiveAndExclusiveTime (List<Log> logs){ } Log for some functions, calculate the inclusive time and exclusive time for each function E.g Fun_name enter / exit time F1 enter 1 F2 enter 2 F2 exit 3 F1 exit 4 F1: inclusive time = 41 = 3, exclusive time = 31 = 2 F2: inclusive time = 32 = 1, exclusive time = 1
 Report Duplicate  Flag
Facebook SDE1  0of 0 votes
AnswersFind the subarray within an array (containing at least TWO number) which has the largest sum.
 ajay.raj in United States
For example, given the array [2,1,3,4,1],
the contiguous subarray [2,1] has the largest sum = 3.
try to do it in O(n) time
Followup, if input is stream, how to solve it
public int maxSubArray(int[] nums) {} Report Duplicate  Flag
Facebook Software Engineer  0of 0 votes
Answerstokenize string, "" and [] are token flags, such as
 ajay.raj in United States
mytable "foo" [bar] "" [[[[]]].
"" Turned into ",]] turned into], [[not escaped
The results of the example given above:
mytable
foo
bar "
[[]
public List<String> tokenizestring(String s){
} Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersWhat design pattern is used to implement a SynchronizedHashMap?
 ajay.raj in United States Report Duplicate  Flag
Amazon Java Developer  0of 0 votes
AnswersF (n) = 3n + 1 (if n is odd) or n / 2 (if n is even)
 ajay.raj in United States
Collapse sequence refers to each number according to this formula
until the sequence becomes equal to 1,
Find the number (which is not greater than 10000), which will have the longest Collapse sequence.
public int getlongestCollapsesequence(int n){
} Report Duplicate  Flag
Google SDE1  0of 2 votes
AnswersFind the Lexicographic next word of the input word from a list of words
 ajay.raj in United States
Example
Words list
[Cat, dog, cow, donkey, zebra, monkey],
input
duck
output
monkey
Input
dog
output
donkey
Can you use trie to solve it?
public String findNextWord(List<String> words, String input){
} Report Duplicate  Flag
Google Software Engineer  0of 0 votes
Answerswrite a function to generate a random 4 digit unique even number, the four digits cannot be the same, 1234 is valid, but 1134 is not valid
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  1of 1 vote
Answerswrite a function that randomly return only odd number in range [min, max)
 ajay.raj in United States
public int getRandomOdd(int min, int max){} Report Duplicate  Flag
Google Software Developer  0of 0 votes
AnswersFor a string chemical formula like “C6H2(NO2)3CH3”, and output a map with key as element and value as its count.
 ajay.raj in United States
element can have two chars, for example Fe2(SO4)3
public HashMap<Character, Integer> getCount(String chemicals){
} Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersA "derangement" of a sequence is a permutation where no element appears in its original position. For example ECABD is a derangement of ABCDE, given a string, may contain duplicate char, please out put all the derangement
 ajay.raj in United States
public List<char[]> getDerangement(char[]){} Report Duplicate  Flag
Facebook SDE1  2of 2 votes
Answersthree sum with duplicate, pirnt all indexes, for example:
 ajay.raj in United States
0 2 2 2
(0)(1)(2)(3)
print (0, 1, 2) (0, 1, 3)
can you do it use n^2 (or less) time complexity with as less space as possible?
public List<List<Integer>> threeSum(int[] nums) {} Report Duplicate  Flag
Facebook SDE1  0of 2 votes
AnswersGiven an array of task and k wait time for which a repeated task
 ajay.raj in United States
needs to wait k time to execute again. please rearrange the task
sequences to minimize the total time to finish all the tasks.
Example
Tasks = 111222, k = 2,
One possible task sequence is
12_12_12,
another possible task sequence is 21_21_21
thus you shoud return 8
public int getMiniTime(int[] nums, int k){
}
follow up, output one of the sequence 12_12_12, or 21_21_21 Report Duplicate  Flag
Facebook SDE1  1of 1 vote
AnswersGiven an unsorted array, sort it in such a way that the first
 ajay.raj in United States
element is the largest value, the second element is the smallest,
the third element is the second largest element and so on.
[2, 4, 3, 5, 1] > [5, 1, 4, 2, 3]
can you do it without using extra space
public void sortAlternate(int[] nums){} Report Duplicate  Flag
Facebook SDET  0of 0 votes
AnswersGiven a number of tasks (T) and servers (S), find out if the tasks can be accommodated on the servers. Each Task has a number of Units and each server has a number of Slots on which Units can run.
 ajay.raj in United States
The only condition is that two Units of the same Task "cannot" run on the same Server.
Servers
S[0] = "SS1", "SS2", "SS3", SS4 //Slots // 4 > 3 > 2 > 1
S[1] = "SS1", "SS2" // 2 > 1 > 0 > false
S[2] = "SS1", "SS2", SS3, SS4, SS5 // 5 > 4 > 3 > 2
S[3] = "SS1", "SS2", SS3, SS4, SS5 // 5 > 4 > 3 > 2
Example:
S[0] = 4
S[1] = 3
S[2] = 5
S[3] = 5
...
Tasks
T[0] = U0, U1, U2, U3 //Tasks
T[1] = U0, U1
T[2] = U0, U1, U2
...
Example:
T[0] = 4
T[1] = 2
T[2] = 3
implement
boolean boolean CanRunTasks(S[], T[]){
} Report Duplicate  Flag
Facebook SDE1  2of 2 votes
Answerdeleted
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
Answersclass UndirectedGraphNode { int label; List<UndirectedGraphNode> neighbors; UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<>(); } } public boolean isBipartite(List<UndirectedGraphNode> nodes){ }
use DFS algorithm to check the bipartiteness of a graph
 ajay.raj in United States Report Duplicate  Flag
Facebook SDE1  0of 0 votes
Answers* Definition for a binary tree node.
 ajay.raj in United States
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
Given an array of Binary Tree Node, check if all of these nodes can form a binary tree?
Public boolean canForm(TreeNode[] nodes){
} Report Duplicate  Flag
Google Software Engineer / Developer  0of 0 votes
AnswersGive a Runable interface, and then give a scheduler post method. This post is parallel, for example:
 ajay.raj in United States
Method header:
public void post (Runable r) {};
Call 5 times:
Scheduler.post (r1);
Scheduler.post (r2);
Scheduler.post (r3);
Scheduler.post (r4);
Scheduler.post (r5);
The five runables are allocated to five threads and run at the same time. And then asked: how to achieve these five tasks one by one run, Report Duplicate  Flag
Google SDE1  4of 4 votes
Answersthere is a bunch of tasks, each have different time to complete, task is independent, and then there are some workers,
 ajay.raj in United States
How to allocate tasks to these workers to minimize the total time to complete all the task. The tasks can be randomly picked from the task list.
Example
Task: 2,2,3,7, 1
Worker: 2.
Return 8, because the first worker can work on the first three tasks : 2 + 2 + 3 = 7, and the second worker can work on the last two tasks : 7 + 1 = 8, so the total time to finish all the task is 8.
public int getMini(int[] tasks, int k) Report Duplicate  Flag
Facebook SDE1  4of 4 votes
AnswersGiven an nonnegative int array and target number, check if the target can be equal to the sum of nonnegative multiples of the numbers in the array.
 ajay.raj in United States
For example, I have three numbers 6,9,20. Ex: n = 47 then it can be determined that 47 = 9*3 + 20
n=23 then there are no combinations.
public boolean combinationSum(int[] nums, int target) {
} Report Duplicate  Flag
Google SDE1  2of 2 votes
AnswersFind three nonoverlap windows of size k in an int array, that together has a maximum sum
 ajay.raj in United States
of the 3k entries.
example
int[] nums = [1,2,1,2,6,7,5,1]
k = 2
output
[1,2],[2,6],[7,5] Report Duplicate  Flag
Google Software Engineer  2of 2 votes
AnswersGiven an int array without repeated elements and a target, count the total number of subset that can be generated from the array such that min (subset) + max (subset) < target
 ajay.raj in United States
public int countSubSet(int[] nums, int target){
} Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersData structure design, N horse races, there are 10 checkpoints, whenever a horse through a check point will produce a (horse number, check point number) message, then design a data structure and algorithm to update the messages and then get the top 3 horse efficiently.
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersInput friend’s relation {{1,2}, {2,3}, {3,4}}, could you split all the users into two groups and for the user in each group, all the users do not know each other. So the expected output should be group1 {1,3}, group2 {2,4}. If it is cannot be spitted into two group, just return “impossible”
 ajay.raj in United States Report Duplicate  Flag
Google SDE1  0of 0 votes
AnswersGiven an array that contains both positive and negative integers, find the start and end index of the subarray that achieves the maximum subarray product using one pass
 ajay.raj in United States Report Duplicate  Flag
Google  0of 0 votes
Answershow to find leaf node value from preorder sequence of BST without rebuilding the tree
 ajay.raj in United States Report Duplicate  Flag
Google Software Engineer  0of 0 votes
Answersdeleted
 ajay.raj in United States Report Duplicate  Flag
Google Software Engineer  2of 2 votes
AnswersSay you have an array for which the ith element is the price of a given stock on day i.
 ajay.raj in United States
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
, but each time you sell you need to pay transaction fee, please calculate the maximum profit you can take.
public int maxProfit(int[] prices, int fee) {
} Report Duplicate  Flag
Google  0of 0 votes
Answersfor a binary tree, print the root to the leaf path, but add "_" to indicate the relative position.
example:
 ajay.raj in United StatesA / \ B C / \ / \ D E F G output _ _ A _ B D _A B _E A _C F A _ C _ _ G
 Report Duplicate  Flag
Google Software Engineer  0of 0 votes
Answers/**
 ajay.raj in United States
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
Given a list of intervals, and a target interval
Our goal is to merge these intervals, so that the results of the merge can cover the target interval, return the minimum number of the original interval required for this merge
For example
IntervalList: [1, 9] [1, 10] [0, 3] [9,10] [3, 14] [2, 9] [10, 16]
Target interval: [2, 15]
we find that there are several ways to cover [2,15], such as:
[1, 9] + [9,10] + [10, 16] or [1, 10] + [10, 16].
We want to merge the least number of ways, so here should return 2 Report Duplicate  Flag
Google SDE1  4of 4 votes
Answers/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
Find if a given binary tree has duplicate sub trees.
followup:
Find all duplicate subtrees in a binary tree
 ajay.raj in United StatesFor example, 1 / \ 2 3 / / \ 4 2 4 / 4 The following are two duplicate subtrees: 2 / 4 and 4 Therefore, return [ [2,4], [4] ].
 Report Duplicate  Flag
Google Software Engineer / Developer  0of 0 votes
Answercount Number of balanced Binary Tree given Preorder Sequence length
 ajay.raj in United States Report Duplicate  Flag
Amazon SDE1  6of 6 votes
AnswersPaper Cut into Minimum Number of Squares
 ajay.raj in United States
Given a paper of size A x B. Task is to cut the paper into squares of any size. Find the minimum number of squares that can be cut from the paper.
Examples:
Input : 13 x 29
Output : 9
Explanation :
2 (squares of size 13x13) +
4 (squares of size 3x3) +
3 (squares of size 1x1)=9
Input : 4 x 5
Output : 5
Explanation :
1 (squares of size 4x4) +
4 (squares of size 1x1)
geeksforgeeks provides a solution, but it is not right
http://www.geeksforgeeks.org/papercutminimumnumbersquares/ Report Duplicate  Flag
Google  0of 0 votes
AnswersGiven a diamond shape matrix, find the minimum path sum from top to bottom.
Each step you may move to adjacent numbers on the row below.
 ajay.raj in United States[ [2], [3,4], [6,5,7], [4,1,8,3], [2,5,4], [6,4], [1] ]
 Report Duplicate  Flag
Amazon Software Engineer / Developer  0of 0 votes
AnswersDesign a algorithm to initialize the board of Candy Crush Saga. With M x N board, Q types of candies. (Rules: no 3 for run after initialization, must contain at least one valid move at the beginning)
 ajay.raj in United States Report Duplicate  Flag
Facebook Software Engineer / Developer  0of 0 votes
AnswersIf a string is matched to any filter, it is in the black list, otherwise not.
 ajay.raj in United States
Design a data structure and implement following two functions.
addFilter(filter)
isInBlackList(string)
filters are in the form of
“a*b”
“abc”
“aa*b”
having at most one star, which matches 0 or more chars. Report Duplicate  Flag
Amazon Software Engineer
how about this one?
#include <iostream>
#include <vector>
using namespace std;
int minsum(vector<vector<int>> &nums){
int n=nums.size();
if(n==0) return 1;
for(int i=1;i<n;i++){
for(int j=0;j<nums[i].size();j++){
// fom top to middle
if(nums[i].size()>nums[i1].size()){
if(j1>=0&&j<nums[i1].size()){
nums[i][j]+= min(nums[i1][j1],nums[i1][j]);
}else if(j==0){
nums[i][j]+=nums[i1][j];
}else{
nums[i][j]+=nums[i1][j1];
}// from mid to bottom
}else{
nums[i][j]+=min(nums[i1][j],nums[i1][j+1]);
}
}
}
return nums[n1][0];
}
/*
[
[2],
[3,4],
[6,5,7],
[4,1,8,3],
[2,5,4],
[6,4],
[1]
]
*/
int main() {
vector<vector<int>> nums={{2},{3,4},{6,5,7},{4,1,8,3},{2,5,4},{6,4},{1}};
cout<<minsum(nums);
/*for(auto num:minsum(nums)){
for(auto n:num)
cout<<n<<" ";
cout<<endl;
}*/
//cout<<"Hello";
return 0;
}

ajay.raj
March 02, 2017
Rep
RepEarned praise for analyzing acne for the government. Earned praised for my work implementing mantra to get desired husband in ...
RepNancy Nash, Area Sales Manager at Absolute Softech Ltd
Prior to my current job I was training soap scum in Africa. Earned praised for my work developing wooden trains ...
RepEdwards IVF Surrogate is one of the best & most successful provider of surrogate services.We provide moral, emotional, ethical and ...
Reprameshdondu15, Analyst at ASAPInfosystemsPvtLtd
My name is Ramesh dondu from India. I burn through 2009 to on words consistently work in Interior planner. I ...
RepAre you looking a solution for marry your love? Islamic dua to marry someone you love is the effective solution ...
RepLove is the spice of everyone’s life. Love adds charm and excitement to the monotonous and boring life. If ...
RepPandit Ji is the best vashikaran expert for vashikaran mantra for girlfriend in Mumbai.It is the strongest method to ...
Repstanjachrissi, Integration Software Engineer at xyz
Hi,my name is Stanja Chrissi. I was conceived and FL. I moved on from CA and went ahead to ...
Replovevashikaranmantrasolution, Data Engineer at ASAPInfosystemsPvtLtd
Are you searching the mantra for your lost love boyfriend? BabaJi will guide you with simple and effective mantra to ...
RepWant to know how to protect from black magic? Guru Ji is the world’s famous astrologer and he has ...
RepLooking for the best day care center Charlotte? PalARoo’s Child Development Center is a family owned child care facility ...
RepSpent 20012006 getting my feet wet with Slinkies in Fort Walton Beach, FL. mantra to control girl Spent 20012006 working ...
RepPrestige Luxury Rentals, Tech Lead at Prestige Luxury Rentals
Prestige Luxury Rentals is highly recommended company for exotic car rental Miami. With our top brand vehicles like; exotic, luxury ...
RepOur mission is to provide informative and Self Improvement advice to help people live their lives better set definite goals ...
Rep
RepAmber Van is the top rated company that offers friendly and professional removals services.Our featured services includes domestic moves ...
Rep
RepAre you searching for the most powerful and very strong mantra for your husband? If you want to do Jadoo ...
Repadelazhang156, Personnel at Boeing
My name is Adelaz Hang. I am from Georgia USA. I am list month finish 31 years. I am chief ...
RepJonathan Galgano, Data Engineer at Blue Jeans
Drive with the most affordable Exotic Car Rental South Beach. Prestige luxury Rentals is offering you with the finest car ...
RepJohn Colcomb, Analyst at A9
With more than 20 years of car rental and dealership experience, responsible for developing growth strategies to maximize operational effectiveness ...
RepDeveloped several new methods for licensing g.i. joes in Los Angeles, CA. Spent high school summers creating marketing channels ...
RepLarry Alvarez, Analyst at ASU
Prestige Luxury Rentals is one of the most renowned car rental companies in USA. We are locally owned and operated ...
RepSherryellis555, Computer Scientist at ASAPInfosystemsPvtLtd
My name is Sherri Ellie Once had a fantasy of testing the market for tar in Georgia, GE. Rehearsed in ...
RepSCREENish employee time tracking software can be used as desktop or mobile app. Once the employee has tracked his working ...
RepSergeykrestov156, System Administrator at Cerberus Capital
Hi everybody! I'm Sergey Kreston Hill New York and I'm an understudy of the Masters in Entrepreneurship and ...
Rep
RepBlack magic mantra is simple and easy mantra. Call our specialist today for advice on black magic mantra to kill ...
RepGerard Swearingen, Consultant at ADP
Want to book exotic and luxury car rental in Atlanta, GA ? We, Prestige Luxury Rentals are the best car rentals ...
Repfesfporyi212, Member Technical Staff
My self Fesfpory. I work in agriculture university in India as a professor. I done PHD in Botany in Punjab ...
RepAlisonjaeger755, Data Engineer at Accolite software
I am work in Telecom line in IDEA company. I am data operator and Engineer in back end in Idea ...
Repastroamitji, Trust and Safety Engineer at Boeing
My name is (Canada Toronto). I'm in my last year in the CMOS program. I'm initially from Aminos ...
RepDo you want to use Kamdev Vashikaran Mantra to subdue someone?Or If you are willing to attract your love ...
RepDaniel Wattss, Cloud Support Associate at A9
Spent 20012007 getting to know pogo sticks for no pay. Enthusiastic about researching deodorant in Los Angeles, CA. Prior to ...
Open Chat in New Window
rsrs3
 ajay.raj May 04, 2017for {"an","dan", "c"}, your codes return [[an], [c], [dan]]
but it should be [[c], [an, dan]]