NoOne
BAN USERLook at that link there? That is the language we have created.
 2of 2 votes
AnswersGiven an unsorted array of integers, find the length of the longest consecutive elements sequence.
 NoOne in India
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4].
Return its length: 4.
Your algorithm should run in O(n) complexity. Report Duplicate  Flag  PURGE
Uber Senior Software Development Engineer Algorithm  1of 1 vote
AnswersThe stock exchanges work with price matching. A seller comes with a price, and a buyer, given asking for the exact same price are matched, and in quantity.
 NoOne in India
Design a system that works.
Considerations:
1. More than a million buy/sale happens in a second.
2. One needs to show a ticker prices  last sold price of a stock. Report Duplicate  Flag  PURGE
Myntra Software Architect Algorithm  0of 0 votes
AnswersCreate a data structure that stores integers, let then add, delete. It also should be be able to return the minimum diff value of the current integers.
 NoOne in India
That is,
min_diff = minimum (  x_i  x_j  )
Example:
1,3,4,10,11,11
min_diff = 0
1,3,4,10,11,14
min_diff = 1 Report Duplicate  Flag  PURGE
Uber Senior Software Development Engineer Algorithm  0of 0 votes
AnswersThe original question can be found from here :
 NoOne in India
franklinchen.com/blog/2011/12/08/revisitingknuthandmcilroyswordcountprograms/
Read a file of text, determine the *n* most frequently used words, and print out a sorted list of those words along with their frequencies.
In the same spirit of the history:
1. Do it using pure shell scripting
2. Do it in the favourite language of your choice
Try to minimise code and complexity. Report Duplicate  Flag  PURGE
Deshaw Inc Software Developer Algorithm  0of 0 votes
Answer1. If I say quick sort takes O(e^n ) on the average, would I be wrong?
 NoOne in India
2. Do you think O( f ) is a good idea for real engineering?
3.Given a choice, what other 'order of' measure would you propose to use ?
4. Do you see a real problem with the modified *order of* ?
5. If you were to sort 10 elements, what sorting method would you have used?
6. If you were to sort 1 trillion unicode characters, what sorting method you would have used? Report Duplicate  Flag  PURGE
Microsoft SDET Algorithm Math & Computation  0of 0 votes
AnswersThe actual problem from question?id=6289136497459200
Implement pow, with :// Assume C/C++, as of now double pow ( double x, double power )
No library functions allowed.
Should return : x^power
=== Edit ===
People took it a bit trivially, thus examples should help :
 NoOne in United Statesx = pow ( 4, 0.5 ) // x = 2.0 x = pow ( 8, 0.333333333 ) // 1.99999999986137069 x = pow ( 10.1 , 2.13 ) // 137.78582031242644
 Report Duplicate  Flag  PURGE
Microsoft SDET Algorithm  0of 0 votes
AnswersFrom here : question?id=5660692209205248
 NoOne in United States
Inorder traversal:
A>B>C>D>E>F>H>L>MP>R>S>T
Write a function (pseudocode is fine) that given a starting node, advances to the next inorder node in a binary tree.
Please also provide a datastructure definition of a node. Report Duplicate  Flag  PURGE
Arista Networks Software Developer Algorithm Trees and Graphs  0of 0 votes
AnswersApparently DESCO asked it. It was faulty, and I am fixing it. The physics was wrong. A mono pole is an abstract magnet with either the north or the south pole of the magnet.
[ en.wikipedia.org/wiki/Magnetic_monopole ]
Imagine you are given such *n* monopoles, all of the same type, say North type. Thus, all of these repel one another. The force of repulsion follows inverse square law :
[ en.wikipedia.org/wiki/Inversesquare_law ]
That is, given two such monopoles with a distance *r* between them, the force of repulsion between them is given by :F = ( 1.0 ) / ( r ** 2 )
Now, suppose you are also given an array of *n* number of positions over X axis, like : [ 0, 1, 4, 10 , 21 , .. ] where you need to place the monopoles ( imagine they are hold tight there, and do not move away ).
 NoOne in United States
After placement, you are given another monopole, of different type S, say. Find positions to place the monopole so that it is stable.
Fixes from the original question :
[geeksforgeeks.org/deshawinterviewexperienceset19oncampus/ ]
1. Monopoles exhibit inverse square law, not inverse law.
2. It is impossible to have stable configuration using same type monopole, so one must use another type, repulsion is not stable, attraction is.
( Terrible physics mistakes )
PS. Do not try to do binary search here. Binary search assumption is underlying linearity of the structure, thus, effectively there are proportionate elements in left and right. In the classic cases of sorted array, the expectation is 50/50. But here due to non linearity (inverse square) , it won't work. Report Duplicate  Flag  PURGE
Deshaw Inc Software Developer Algorithm  0of 0 votes
AnswersGiven a set of numbers, find out all subsets of the set such that
the sum of all the numbers in the subset is equal to a target number.s = [ 1, 2, 3, 4, 5 ] target = 5 op = [ [ 1,4 ] , [2,3] , [5] ]
Application: Given a fixed budget, and work items we are doing back filling to check what all we can attain with the budget.
Continuation. Imagine the set is actually a set of work items, with cost and utility involved :def work_item : { name : 'foo bar' , cost : 10 , utility : 14 }
Now, solve this to maximise utility.
Continuation. Imagine that the work items are related, so that, if work item w1 is already in the
subset of the work items selected, w2 's utility increases further!.
( Can you imagine how it can happen? Effectiveness of Mesi increases when he plays for Barca)
So, you are given a list like this :w1 > normal utility 14, with w2 20, ....
Now maximize payoff.
NOTE: Payoff is a matrix. This comes from game theory.
Hence, a payoff matrix looks like :w1 w2 w3 w4 .... w1 w1 w2 w2 w3 w3 w4 w4
A cell ( i,j) is filled up with if a list contains both wi and wj, then how much the payoff would be. It is a symmetric matrix.
 NoOne in United States Report Duplicate  Flag  PURGE
Amazon SDE3 Algorithm  0of 0 votes
AnswersWe tend to use computer to solve practical problems that actually earns or save dollars. Here is something that happens across the stock exchanges : people buy and sell stocks.
 NoOne in India
We generally use automated intelligent systems to buy and sell stocks. That part is too much mathematics, and beyond scope of this interview. There is another part. Suppose the system issues a buy order : buy 1000 Microsoft stock. Now, there are more than 1 ( in fact 10 ) active exchanges from where we can buy MSFT. There is a slight price delta, which keeps changing over time. There is another problem. In each stock exchange, prices are stacked, that is :
1. For first 100 stocks prices are 55$.
2. Next 200 stocks, prices are 55.2$.
... etc, and you got the idea. Even this stacks are changing over time.
Thus, here is the problem to solve. Design and implement a system such that one can buy n stocks with minimal price.
Also, in the same spirit, the same system should be able to sell n stocks with maximum payoff possible.
This is a non trivial problem, for Quant systems.
There are always k no of exchanges to hit. Report Duplicate  Flag  PURGE
Goldman Sachs Software Engineer / Developer Algorithm Cache Computer Architecture & Low Level Computer Science Distributed Computing Large Scale Computing Math & Computation Software Design  0of 0 votes
AnswersAs you know, Computers were invented to solve practical business problems, we tend to ask practical applied questions. One of the key areas where we want to apply computers is simulation. As most of the people working in software are Engineers, here is the problem. It is called 3 body problem.
 NoOne in India
3 Bodies with masses [ m1, m2, m3 ] are initially positioned in the 3 points in the space, thus, having positions [ P1, P2, P3 ].
Observe that each Pi is nothing but [ xi, yi, zi ].
Once the initial condition is set, definitely gravity would work and they would start falling against each other. Write code to simulate this problem. Imagine G, the constant of gravity as 1.
How do you go about simulating it?
Hint : feynmanlectures.caltech.edu/I_09.html see 9.5
Face to face. Pen and Paper. Panel Interview, 2 person Panel. 60 Minutes. For Engineers only, was specifically told about it. Report Duplicate  Flag  PURGE
Software Developer Algorithm Computer Science Graphics Math & Computation Programming Skills  0of 0 votes
AnswersGiven a convex polygon ( is planer as opposed to a polytope) and a point one had to tell if the point lies inside the polygon or outside the polygon.
 NoOne in India
To understand convexity : mathopenref.com/polygonconvex.html
Thus the question comprise of 3 sub problems :
1. How to store a polygon.
2. How to define inside and outside of a polygon.
3. How to solve the actual one, given 1,2 ? Report Duplicate  Flag  PURGE
Deshaw Inc Software Developer Algorithm  0of 0 votes
AnswersAs you guys know, C did not have,and does not have anything called class. C++ has them. Now, C++ was written using C. In fact, C++ initially was called C with classes.
 NoOne in India
Thus, here is the problem for you.
Given you have C, and you need to implement class like behaviour, how you would do it? Specifically, implement the following in C :
1. A Simple Hello class with hello() function printing "Hello, World" .
2. A new operator which enables creating this constructor less class.
3. A delete operator that deletes the pointer.
How would you do it? Report Duplicate  Flag  PURGE
Deshaw Inc SDET C  0of 0 votes
AnswersLinux has this nice command called *tree*.
 NoOne in India
If you did not use it, please take a look around.
You do not have to write one. BUT, you have to do something similar. Given a file name ( not a path ), and an initial directory, you have to list all the file paths, which matches the file name, case should not be considered.
Also allow regex match.
Again, the problem is non trivial.
It was expected to ask the right questions. Report Duplicate  Flag  PURGE
SDET Algorithm Operating System  0of 0 votes
AnswersThere is this nice tiny *nix utility called *wc*.
The idea here is :wc file_name
prints :
 NoOne in India
character count of the file.
Word count of the file.
Line count of the file.
You have to implement your own *wc* program.
NOTE: The problem is non trivial for 3 reasons.
It was expected to ask about the non triviality. Report Duplicate  Flag  PURGE
SDET Algorithm Operating System  0of 0 votes
AnswersNone actually understands how garbage collection works, albeit people ask this in the interviews. Nonetheless, we are going to ask you something very similar. Here is the problem.
Take an array of bytes, perhaps 1MB in size.
Implement these two operations:ptr_structure = alloc ( amount_of_storage ) freeed = free ( ptr_structure )
Now, here is your problem. alloc must allocate contiguous storage. If it is not possible, you need to compact ( defragment ) memory. So, you need to implicitly write a :
defragment() // defragments memory
Worse is coming. Even imagining you have written a stop the world defragmenter, after you reallocate, how the ptr_structures would actually work?
 NoOne in India
Solve this whole problem.
Time allocated was 1 hour. Face to face, panel with 2 interviewers. Report Duplicate  Flag  PURGE
SDET Algorithm Assembly Computer Architecture & Low Level Computer Science Data Structures  0of 0 votes
AnswersImagine there are brick boulders, all of integer size.
Their sizes are stored in an array.
The figure looks something like this :
peltiertech.com/Excel/pix2/Histogram2.gif
Now, suppose someone is pouring water into it till water starts spilling.
You have to answer how much water the boulders are holding up.
 NoOne in Indiadef water_holding( arr ) { /* answer this */ }
 Report Duplicate  Flag  PURGE
Deshaw Inc SDET Algorithm  0of 0 votes
AnswersXPATH implementation problem.
 NoOne in India
Here is the problem.
Implement XPATH expressions, given there is a DOM tree :
1. $x('//*[text() = "abc"])
How do you think it is implemented? Write code, imagine you have a general purpose tree.
2. $x('//span[text() = "abc"])
How do you think it is implemented? Write code, imagine you have a general purpose tree.
Now, explain which one would be faster, and why?
Explain from the design and the code you have written. Report Duplicate  Flag  PURGE
SDET Algorithm Application / UI Design  0of 0 votes
AnswerAs you know, every OS comes up with this tiny application called the calculator. It is good. Now, here is our problem. If we try to implement the function
def calculate( operand, operator, operand ) { /* Do Interviewers bidding here */ }
I have to write if upon if upon if upon if to do for all operators. Moreover, some operators are not even binary! Take example the abs() or say the negate()!
 NoOne in India
Bigger problem persists. With the if mode, we can not even add operators as we wish to without changing code!
But that is a sin. So, what do we do? That is question 1.
In question 2, as a software tester, how do you propose to test and automate the above? Writing more if than the developer is not allowed. Report Duplicate  Flag  PURGE
SDET Algorithm Data Structures Object Oriented Design Programming Skills Software Design  0of 0 votes
AnswersWe all know databases are very very slow. In fact they are so slow that very serious people who wants to do volumes of read operation and search operations write their own implementation. In this question, you would be asked to do the same, for a very limited operation  select.
Every item stored has this field called timestamp.
Now, here is the problem you need to solve :select items where time < some_time select items where time < some_time and time < another_time select items where time > some_time
Imagine you have millions of data rows. How to store it in HDD, and how to load, entirely your problem. None is going to insert anything on existing data  only read.
 NoOne in India
Write an algorithm that solves this problem, and a data structure that works as storage for the data. Report Duplicate  Flag  PURGE
SDET Algorithm Database  0of 0 votes
AnswersImagine you are given the instructions :
GOTO <LABEL> WHEN <CONDITION> NOP ; no operation
Implement the following using it:
 NoOne in India
1. If condition.
2. If else condition.
3. If else if else condition.
4. While loop
5. for loop. Report Duplicate  Flag  PURGE
SDET Assembly  0of 0 votes
AnswersGiven brackets, e.g. '(' and ')' as the only symbols, write a function that would generate : true, if the brackets are matching, false if the brackets are not matching.
 NoOne in India
Almost everyone can do the above.
Now, prove that it works.
Also tell which class of grammar the string belongs to.
Showcase why your algorithm is a language recogniser for the same. Report Duplicate  Flag  PURGE
SDET Automata  0of 0 votes
AnswersYou are given 20 questions to solve in 20 minutes.
 NoOne in India
If you successfully solve the question, you would receive 2 marks.
If you failed to solve the question, and you do not try it ( let it untouched ) , you would receive 0 marks. If you solve it wrong ( i.e. not the correct answer )  you would receive 1 ( negative) .
With the story, here are the problems:
1. Write an algorithm, which, given an input array ( set ) of questions, and varying probability ( 0 <= p <= 1 ) of can do and can not do per question, generates a strategy for solving the paper to generate maximum expected pay off.
2. Given the question paper is multiple choice, between 4 choices ( a,b,c,d ) do a bias analysis ( e.g. if more a's are coming than 'c's ), and decide if you would like to probabilistically take risk and mark some to increase pay off.
Obviously, you can get a maximum 40, and a minimum 20.
3. Now, put yourself in the position of the examiner, and try to ensure it is almost impossible to increase payoff by random selection over the questions. Try to negate the bias. That is question 3.
In all 3 cases write an algorithm. Face to face interview, time allocated was 60 minutes. Panel Interview. Report Duplicate  Flag  PURGE
unknown SDET Algorithm  0of 0 votes
AnswersFind the n'th Ugly no. An ugly no. is defined as a no. which are of the form :
n = ( 2 ** p ) * ( 3 ** q ) * ( 5 ** r )
with p,q,r >= 0 and are integers not all equal to zero.
 NoOne in United States
You must not memorise the whole sequence, as n can be really large.
Hint : use number theory to figure out the pattern of the increasing sequence. Report Duplicate  Flag  PURGE
Algorithm  0of 0 votes
AnswersGiven an array, move the smaller no to the left and the larger nos to the right. The relative positioning between the small no's and the relative positions between the large nos should not change.
The original ( ill formulated ) question can be found here :
question?id=5756583549075456.
Example :a = [ 6 4 5 0 2 1 11 1 ] after_a = [ 0 , 2, 1, 1, 6, 4, 5, 11 ]
Note, for lack of good explanation, please do not laugh at the poster in the solutions. After all, they are trying to help or get help.
 NoOne in United States Report Duplicate  Flag  PURGE
Arrays
A very complex  and *tries to be smart* approach. Not entirely sure if it is worth it, I would suggest  NO.
num_lists = 5
// create a list of lists
ll = list( [0: num_lists ] ) > {
list([0:10]) > { random(30) }
}
println ( ll )
// smarter approach
d = fold( ll, dict() ) > {
for ( inx : [0:size(ll)] ){
l = ll[inx]
for ( item : l ){
if ( item @ $.p ){
$.p[item] += inx
} else {
$.p[item] = set(inx)
}
}
}
$.p
}
// find all items that existed in more than one lists
entries = select ( d ) :: { size( $.o.value ) >= 2 }
println ( entries )
// make pairwise
all_pairs = fold ( entries , dict() ) > {
list_indices = $.o.value
// create pair from values
pair = comb( list_indices , 2 )
for ( p : pair ){
k_p = str(p,',')
if ( k_p @ $.p ){
$.p[k_p] += $.o.key
} else {
$.p[k_p] = list( $.o.key )
}
}
$.p
}
println ( all_pairs )
// select all entries with value length more than 2
valid_list_pairs = select ( all_pairs ) :: { size( $.o.value ) > 2 }
println ( valid_list_pairs )

NoOne
January 10, 2017 This is how it looks like in ZoomBA :
num_lists = 5
// create a list of lists
ll = list( [0: num_lists ] ) > {
list([0:10]) > { random(30) }
}
println ( ll )
// naive approach
pairs = join ( [0:num_lists], [0:num_lists] ) :: {
i = $.0 ; j = $.1
continue ( i >= j )
intersection = ll[i] & ll[j]
size( intersection ) >= 3 // that is the condition ?
}
println ( pairs )

NoOne
January 10, 2017 In recursive mode, we can do cool in ZoomBA :
def do_join( tuple, arr, result ){
i = size(tuple)
if ( i == size(arr) ){
result.add ( tuple )
return
}
for ( item : arr[i] ){
do_join ( tuple + item, arr, result )
}
}
s1 = [0,1,2]
s2 = [true, false]
arr = [s1, s2]
result = list()
do_join( [], arr, result )
println ( result )

NoOne
December 22, 2016 This is how you do it :
si = set(1,2,3)
sf = set(1.0,2.0,3.0)
sb = set( true, false )
// generate cross product? very well :
p = si * sf * sb
// not satisfied ?
p = join ( si, sf, sb )
// want to load from array ?
p = join ( @ARGS = [ si, sf, sb ] )
// so, you wan to seriously code? Not cool.
In that case, here is how ZoomBA implemented join operation :) from ZoomBA with love:
// full iterative version, w/o any stack or recursion, should be good to watch...
static boolean next(Object[] tuple, List<Iterator> states, Iterable[] cc) {
boolean carry = true;
for (int i = cc.length  1; i >= 0; i) {
if (!carry) break;
Iterator iterator = states.get(i);
if (iterator.hasNext()) {
tuple[i] = iterator.next();
carry = false;
} else {
if (i == 0) return true;
carry = true;
iterator = cc[i].iterator();
tuple[i] = iterator.next();
states.set(i, iterator);
}
}
return false;
}
public static Collection join(Collection into, Function predicate, Function map, Iterable[] cc) {
if (cc.length < 2) return into;
int index = 0;
Object[] tuple = new Object[cc.length];
List<Iterator> myStates = new ArrayList<>();
for (int i = 0; i < cc.length; i++) {
Iterator iterator = cc[i].iterator();
if (!iterator.hasNext()) return into;
tuple[i] = iterator.next();
myStates.add(iterator);
}
boolean carry = false;
while (!carry) {
Function.MonadicContainer result = predicate.execute(index, tuple, cc, into);
if (!result.isNil() && ZTypes.bool(result.value(), false)) {
result = map.execute(index, tuple, cc, into);
extractResult( into, result, tuple );
}
if (result instanceof Break) {
extractResult( into, result, tuple );
break;
}
carry = next(tuple, myStates, cc);
index++;
}
return into;
}

NoOne
December 22, 2016 In ZoomBA, or rather any other language, the logic should be clear like this :
// get file iterator  line by line
fi1 = file('large1.txt')
fi2 = file('large2.txt')
fo = open('merged' ,'w')
// when both are non empty  interleave
while ( fi1.hasNext && fi2.hasNext ){
fo.println( fi1.next )
fo.println( fi2.next )
}
// when one is leftover, find it and drop lines
if ( fi1.hasNext  fi2.hasNext ){
leftover = fi1.hasNext ? fi1 : fi2
while ( leftover.hasNext ){
fo.println( leftover.next )
}
}
// do not forget to close
fo.close()

NoOne
December 20, 2016 Singly linked list, so you use auxiliary data store, a stack works, better, a string works with a special character for separator, like "#".
You simply traverse the linked list and push to the stack, or to the string with "#" , e.g
1 > 2 > 3 > 42 > 3 > 2 > 1
will be encoded as :
1#2#3#42#3#2#1
Now, traverse from left ( head ) again, pop the stack, and match the values.
In case you are using a String, then split the string and then traverse from right.
In case they match always, we have a solution.
Error out in case there is no match.
We can try to be clever and use some x,2x pointer to reach to the middle. But, as of now, that pointer game is pointless.
/*
One way, as Chris said,
for n chars, 2^n for sure,
but then sort these no.s such that
the comparison is how many 1's the binary string has.
Now, iterate and find the binary string with 1 means deletion of char
where the new word after deletion is into dictionary
*/
def find_word( word , dictionary ){
n = #word
l = list([1: 2 ** n ]) > { s = str($.o, 2) ; '0' ** ( n  #s) + s }
sorta( l ) :: {
ls = sum( $.left.value ) > { $.o == _'1' ? 1:0 }
rs = sum( $.right.value ) > { $.o == _'1' ? 1:0 }
ls  rs
}
fold( l , null ) :: {
s = select ( $.o.value ) :: { $.o == _'0' } > { word[$.i] }
w = str(s,'')
break ( w @ dictionary ){ w }
}
}
dictionary = set ( 'fellow' , 'hello' , 'one' , 'hell' , 'fhel' )
word = 'fhellowne'
println ( find_word( word, dictionary ) )

NoOne
December 16, 2016 A much cleaner way in ZoomBA :
my_vals = [ 0, 1, 2, 3 ]
// minimizing use of English and more math
def power_set( arr ){
len = size( arr )
// this is why it is 2^n
list ( [0 : 2 ** len ] ) > {
bs = str( $.o , 2 ) // binary string format
// to make it sized n binary digits
bs = ( '0' ** ( len  size(bs) ) ) + bs // pad 0's to the left
// select the index i's item when bs contains 1 at index i
select( bs.value ) :: { $.o == _'0' } > { arr[$.i] }
}
}
println ( power_set( my_vals ) )

NoOne
December 15, 2016 /*
ZoomBA powerset is simply done by
the following
*/
my_vals = [ 0, 1, 2, 3 ]
// sequences() function generates all possible sub sequences
// which is the power set :)
fold ( sequences(my_vals) ) > { println($.o) }
// in a sensible way, this is how you can do the same
// also explains why it is Theta( 2^n )
def power_set( arr ){
len = size( arr )
n = 2 ** len
for ( bn : [0:n] ){ // this is why it is 2^n
bs = str( bn, 2 ) // binary string format
// to make it sized n binary digits
bs = ( '0' ** ( len  size(bs) ) ) + bs // pad 0's to the left
// select the index i's item when bs contains 1 at index i
subseq = list( bs.value ) > { continue( $.o == _'0' ) ; arr[$.i] }
println ( subseq )
}
}
power_set( my_vals )

NoOne
December 15, 2016 Sorting is not an entirely good idea here,
we do not need it. We can solve it w/o sorting, and in linear time.
Specifically, we can solve it in 2n, in fact, we can solve it in exact n, e.g. in a single traversal. But first, I would showcase 2n in ZoomBA :
data = [ [ 'Student1', 20, 40, 65],
[ 'Student2', 35, 40, 50],
[ 'Student3', 10, 55, 65] ]
// for 3 subjects... can be generalized ...
max = list([0:3]) > { 1 } // hoping scores do not become ve
max = fold ( data , max ) >{
row = $.o ; max = $.p
for ( i = 1 ; i < 4 ; i += 1 ){
if ( row[i] > max[i1] ){
max[i1] = row[i]
}
}
max // return
}
// next, pick and group toppers student > topped_in_sub_count
// select those who are topper in more than n subjects ?
n = 2
toppers = fold( data ) > {
row = $.o
count = sum ( [1:4] ) > { row[$.o] == max[$.i] ? 1 : 0 }
continue ( count < n ) // ignore when count is < n
[ row[0] , count ] // return
}
println( toppers )

NoOne
December 14, 2016 I think ChrisK did a mistake this time, a rarity.
Suppose there are K options, then 3^K is correct.
But if the steps taken are n, then 3^n is wrong, why? Because set n = 1.
Clearly one can make only 1 step, 1 way.
If n = 2, then one can make 1 + 1 or 2, so 2 ways.
If n = 3, then one can make 1 + 1, 2 + 1, 1 + 2, 3 > 4 ways.
Thus, the pattern is :
n < 1 : 1
n = 1 : 1
n = 2 : 2
n = 3 : 4
...
Giving: ( it is a rip off of Generalized Fibonacci like sequences )
S(n) = S(n1) + S(n2) + S(n3)
=====
S(3) = S(2) + S(1) + S(0) = 4
S(4) = S(3) + S(2) + S(1) = 4 + 2 + 1 = 7
=== is it correct? Let's verify ? ====
1 + 1 + 1 + 1
1+1 + 2
1+ 2 + 1
2 + 1 + 1
2 + 2
1 + 3
3 + 1
===> Yess! ( or I am totally wrong? )
// ZoomBA let's you use sequences
steps = seq( 1,1,2 ) > { $.p[1] + $.p[2] + $.p[3] }
n = 5
total = fold ( [3:n+1] ) > { steps.next }
println( total )

NoOne
December 11, 2016 In ZoomBA:
// returns 1 if does not go bye bye,
// else returns the index
will_bye_bye( n , J ){
// one liner in ZoomBA
r = [1:n+1]
for ( i = 0 ; i < size(J) ; i+=1 ){
// select those whose index is divisible by the item index
r = select ( r ) :: { J[i] /? ($.index + 1) }
if( empty(r)  r[1] != n ){ return i }
}
return 1
}

NoOne
December 09, 2016 In ZoomBA, this is how you write it :
def TreeNode : {
val : null , // value
child : list() // list of children
}
def find_parents( cur, nodes , map ){
// check if cur.child and nodes has intersection ?
children = cur.child & nodes
if ( !empty( children ) ){
// append to the map : key > child, value > parent
map = dict( children ) > { [ $.o , cur ] }
nodes = children // remove parented children
}
for ( child : cur.child ){
find_parents ( child, nodes, )
}
}
def delete( root , nodes ){
parents = dict()
// populate parents
find_parents ( root, nodes, parents )
// populated now
for ( pair : parents ){
// remove the child
pair.value.child = pair.key
// reparent childs children into parent
pair.value.child += pair.key.child
}
}

NoOne
December 09, 2016 srterpe very cleverly inverted the problem. I love the idea. Hats off.
Instead of finding all possible words (sub sequences)
a string can generate, which is my stupid idea,
srterpe is counting the no of characters on each word,
and is a word can be made by taking / loaning characters from the string.
Very very clever.
My code has no chance surviving in more then 24 letter strings  he will win hand down for any string with size more than 20 ish  which is the size of a dictionary ( 2^20 ) .
srterpe is slightly off on the complexity, my algo runs with a complexity of Theta(2^n) where n is the size of the input string, it is close to n! where srterpe is correct.
No matter how large the string becomes, srterpe's method would be on size of the dictionary * no of char in the word.
See more on [ en.wikipedia.org/wiki/Longest_word_in_English ]
Here is to srterpe :
DICT = [ "go","bat","me","eat","goal", "boy", "run" ]
list_of_msets = list ( DICT ) > { [ mset( $.o.value ) , $.o ] }
LETTERS = [ _'e' , _'o' , _'b', _'a' , _'m', _'g' , _'l' ]
mset_letters = mset( LETTERS )
words = select( list_of_msets ) :: { $.left <= mset_letters } > { $.right }
println( words )

NoOne
December 08, 2016 Trick question.
Observe the string to counter mapping can be done by (ZoomBA):
strings = { "ab" : 0 , "aa" : 1 , "fff" : 2 , ... }
counters = [ 3, 2, 0, ...]
def increment_counter( s ){
idx = strings[ s ]
#atomic{
// make atomic operation : increment
counters[idx] += 1
}
}
Note that, there is no need to lock anything beyond the increment, as every index access are independent! Only access on the same index are not.
 NoOne December 07, 2016In ZoomBA:
/*
To solve this :
1. Create a map with value as key, and index as value.
2. Iterate the list with testing sum (S) S  item is in the map or not.
2.1. If it is,
2.1.1 and the difference in position is
smaller than previous min store as min
2.1.2 Ignore
2.2. If it is not continue to [2]
*/
def solution( arr, S ){
// a map of key ( item ) > item index
map = dict(arr) > { [ $.o , $.i ] }
min = [ 1,1, num('inf') ] // store +infinity as minimum
fold ( arr , min ) > {
diff = S  $.o
if( diff @ map && map[diff] != $.i && $.p.2 > #$.i  map[diff] ){
$.p = [ $.i , map[diff] , #$.i  map[diff] ]
}
$.p // returns
}
}
arr = [1,4,5,3,6,4,2]
#(i,j) = solution( arr , 8 )
printf( '%d,%d\n', arr[i], arr[j] )

NoOne
December 06, 2016 This problem can be imagined as a permutation problem.
Observe the following. Suppose the number *n* has no of decimal digit *d*.
The problem has no solution if d > 10. You can generalise it to any base now.
Now, start with generating permutations of :
*1* out of D = [ 0, 1, 2, ...., 8, 9 ].
Then, *2* out of D ( note for leading 0s )
Then *3* out of D ( note for leading 0s )
....
Finally *d* out of D, and there, we need to find how many of them are smaller then n.
One can theoretically reach that no, given a number.
So, let's solve it for 42.
Clearly for
d = 1 > 19 ( 9 ) options
d = 2 > There are total 10 * 9 options, out of which 9 has leading zeros.
That takes the toll to 81. How many of them are larger than 42 ?
Obvious,
There are [5,6,...9] for the first digit and [0,1,...,9] for the next.
Also there are 4 for first and [3,5,...9] for second digit.
Hence, there are 5 * 9 + 6 unique digited nos greater than 42.
Hence, the total is : 9 + 81  51 = 39
Now, let's verify with ZoomBA:
n = 42
t = sum ( [1: n + 1 ] ) > {
x = str($.o)
#set( x.value ) == #x ? 1 : 0
}
println( t )

NoOne
December 05, 2016 In ZoomBA :
/*
1. we start with the values, and assigning them the keys from pattern
2. If we find a key whose value does not match the word, we failed
3. Else we have succeeded
*/
def matches( pattern , str_list ){
if ( size(pattern) != size(str_list) ) return false
keys = dict()
fold ( str_list , true ) > {
key = pattern[$.i]
word = $.o
if ( key @ keys ){ // key exists
// if the value pointed by the key is the word?
// then ok, else fail
break ( keys[key] != word ) { false }
} else {
// this is new word, make a key,value out of it
keys[key] = word
}
$.p
}
}
pattern = [ 'a' , 'b', 'b' , 'a' ]
string = [ 'cat', 'dog', 'dog', 'cat' ]
println ( matches ( pattern, string ) )

NoOne
December 04, 2016 Chris is right, of course. A potential fix on this can be assumed ( due to the connectivity problem : two nodes might reside in two unconnected components, albeit chance of it is extremely low, unless you are a free node, and have no friends (much like me) ). Some empirical theory suggests that 6 hops generally are good enough to connect any person to another.
Another nice way out is what he said  start at both ends. Check intersection of the nodes of the frontiers. If any time the intersection returns non empty, you have at least a solution.
Think in terms of automata. Every letter in the sample string is a state, which gets activated when a letter matches, and then it waits for the next state, which is the next letter.
Thus, for a sample string > s[i] where s[i] denotes i'th letter, s[0] is the first letter, we have this automata in place ( axiomatic ) with s[1] is the last letter :
( anything not s[0] ) * > s[0] > ( anything not s[1] ) * > s[1] .... > s[1] > end
We are confused about whether or not s[0] should be the first letter and s[1] should be the last letter of the text string  but those are easy to adjust. Thus, the automata can be coded as (in ZoomBA):
def recognize( pattern_string , text_string ){
cur_pattern_index = 0
for ( char : text_string ){
continue ( char != pattern_string[ cur_pattern_index ] )
cur_pattern_index += 1 // matched, so move to next pattern letter
}
return cur_pattern_index == size( pattern_string )
}
println ( recognize('Rdd Waitn' , 'Redmond, Washington' ) )
println ( recognize('Rdd Waixtn' , 'Redmond, Washington' ) )

NoOne
December 04, 2016 Here is something of help:
[ geeksforgeeks.org/countsetbitsinaninteger/ ]
1 Initialize count: = 0
2 If integer n is not zero
(a) Do bitwise & with (n1) and assign the value back to n
n: = n&(n1)
(b) Increment count by 1
(c) go to step 2
3 Else return count

NoOne
December 03, 2016 Here is how you go about it.
First the theory, and then the ZoomBA dance.
/*
The problem can be solved by first
making the given dictionary a dictionary with :
key > sorted letters of a word as string
values > all words who are permutations of the same key
Thus, given an array of letters:
1. we should sort it first.
2. Find all possible sub sequences of the same sorted array
3. For each sub sequence (which would be sorted)
we should check existence as key in the dictionary
and if it does exist, print all words (values) for that key
*/
DICT = [ "go","bat","me","eat","goal", "boy", "run" ]
sorted_dict = mset( DICT ) > { x = $.o.toCharArray ; sorta( x ) ; str(x,'') }
LETTERS = [ 'e' ,'o' , 'b' ,'a' ,'m' ,'g' , 'l' ]
sorta(LETTERS)
for ( sequences ( LETTERS ) ) {
key = str( $,'')
if( key @ sorted_dict ){
println ( sorted_dict[key] )
}
}

NoOne
December 03, 2016 We can do this by combinations.
Observe that we have 64 * 63 possibilities for two queens, and we can change the order.
That is : 2 * 64 * 63 ways one can arrange 2 queens : T
Now, out of them, how many won't be stable?
Observe that a configuration is unstable iff The queens are in the same :
1. vertical
2. horizontal
3. diagonal.
1. Is possible by : 8 * P(8,2) ways : H
2. Is possible by : 8 * P(8,2) ways : V
3. Is possible by : 4 * ( P(8,2) + P(7,2) + ... P(2,2) ) : D
number of ways = T  H  V  D
In ZoomBA lang, you can be as declarartive as you want, and you can mix style.
events = [ ["Jane", 1.2, 4.5], ["Jin", 3.1, 6.7], ["June", 8.9, 10.3] ]
// sort them with field index 1 : e.g. start time
sorta( events ) :: { $.left.1 < $.right.1 }
// create a list of time slots
left = { 's' : events[0].1 , 'e' : events[0].2 , 'c' : 1 } // first one
col = fold ( [1 : #events ], list( left ) ) > {
right = events[$.o]
/* There can be two cases.
1. right is included in left
2. right and left are independent, with no overlap
*/
left = $.p[1] // last one is the left
if ( left.e >= right.1 ) { // overlap
// completely included
continue ( left.e >= right.2 ){ left.c += 1 }
// split the interleaving
left_half = { 's' : left.s , 'e' : right.1 , 'c' : left.c }
middle_half = { 's' : right.1 , 'e' : left.e , 'c' : left.c + 1 }
right_half = { 's' : left.e , 'e' : right.2 , 'c' : 1 }
$.p.pop() // pop the last item added to the list
// add them up
$.p += [ left_half , middle_half , right_half ]
}else{ // non overlap
$.p += { 's' : left.e , 'e' : right.1 , 'c' : 0 }
$.p += { 's' : right.1 , 'e' : right.2 , 'c' : 1 }
}
// return partial
$.p
}
col += { 's' : col[1].e , 'e' : num('inf') , 'c' : 0 }
// now print
println( str( col , ' , ' ) > { str('(%s,%s)', $.o.s, $.o.c ) } )

NoOne
December 02, 2016 // Shows the full declarative power of ZoomBA
tel_dict = { 2 : [ 'a','b','c' ] , 3 : ['d' ,'e' ,'f' ],
4 : [ 'g' , 'h' ,'i' ], 5 : [ 'j', 'k', 'l' ],
6 : ['m','n','o' ], 7 : [ 'p', 'q','r' ,'s' ],
8 : [ 't' ,'u','v' ], 9 : [ 'w' , 'y' ,'z' ] }
// meaningful words?
words = select( file('/usr/share/dict/words') ) :: { #$.o == 7 } > { $.o.toLowerCase }
ph_no = 2742538 // your input : cricket
args = list( str(ph_no).value ) > { tel_dict[ int($.o) ] }
meaningful = join( @ARGS = args ) :: {
word = str( $.o ,'' )
word @ words } > { str( $.o ,'' ) }
println ( meaningful )

NoOne
November 24, 2016 /* ZoomBA
Note that sivapraneethalli is kind of correct.
A much better way to achieve this is to see this :
xy is a palindrome iff :
y = ( x ** 1 ) or
y = ( x[0:2] ** 1 )
As an example :
1. x = abc
y = cba
2. x = abc
y = ba
Thus, a better algo is to store the potential y's as keys to
to a map, and value being that of x in a list.
Hence, we can get it done in two passes.
*/
def find_pair_palindromes( strings ){
map = fold( strings , dict() ) > {
x = $.o
key = str( x ** 1 )
$.p[ key ] = $.i // store index
if ( size(x) > 1 ){
key = str( x[0:2] ** 1 )
$.p[ key ] = $.i // store index
}
$.p // return
}
fold ( strings ) > {
y = $.o
if ( y @ map ){ printf( '%s %s\n', strings[ map[y] ] , y ) }
}
}
listOfWords = list( "shiva" , "and" , "are" , "vihs" , "avihs" )
find_pair_palindromes( listOfWords )

NoOne
November 24, 2016 Here seems to be a Theta(n+k) solution.
/*
Note that to way to do it most optimally is
to generate a indices map from the ranges,
which does not require a sorting.
Once the dictionary is created,
all we do is traverse over the indices range given
[0,k] ; or in ZoomBA [0:k+1] > and print counts
or zero if the index is not found.
*/
range = [ [5,7],[1,4],[2,3],[6,8],[3,5] ]
// this takes ( min to max )
d = fold( range , dict() ) > {
#(b,e) = $.o // items are tuples
for ( i : [b:e+1] ){
// add indices and store counts
if ( i @ $.p ){
$.p[i] += 1
}else{
$.p[i] = 1
}
}
$.p
}
println ( d )
// produce the result
ar = [0:9] // from 0 to 8 indices
fold ( ar ) > { printf ( '%d > %d\n', $.o , $.o @ d ? d[$.o] : 0 ) }

NoOne
November 21, 2016 Simplest is storing into a file, and then use standard sorting techniques to sort them later.
Given the digits are fixed, we can create a directory tree with LSB at the top, and MSB in the leaf, while the leaf storing the number of repetitions.
So, 1023456 would be stored as :
/6/5/4/3/2/0/1/[count=1]
while 1024 would be stored as :
/4/2/0/1[count=1]
Now, what happens when we do postorder traversal on the tree with children in sorted order? All one needs to do is to store the path from root, and reverse it, and then we have our answer. For multiple occurrence, simply repeat the same count no of times, and we are good.
The max depth of that tree would be 8 ish in base 10.
To do Uniform stuff, one needs to do these steps.
1. Get a function > next_higher_permutation( array ) : available from here :
stackoverflow.com/questions/1622532/algorithmtofindnextgreaterpermutationofagivenstring
2. A random no generator to pick large integers from range [0,N)
3. A really large integer container for storing n! ( n factorial ).
Now, the algorithm.
1. Use [2] to generate a number between 0 and n! ( n factorial ) say it is N.
2. Start with the sorted permutation : [ 0,1,2,...n1 ] as array and then apply
next_higher_permutation on the array N times.
// These sort of problems are kids play in ZoomBA
// We first create a regular expression match from the templates given
// Here, we replace 0 > .? to ensure only one char matches for 0
def matching_rows( template_row , all_permutations ){
template = str(template_row,'').replace('0','.?')
select( all_permutations ) :: { str($.item,'') =~ template }
}
// A join result sudoku is valid if and only if
// the column splitting are all unique
def valid_sudoku( m , n ){
!exists ( [0:n] ) :: {
s = set ( [0:n] ) > { m[$.item][$.$.item] }
#s != n
}
}
// get the template
my_template = [ [1, 2, 0], [0, 1, 0], [0, 0, 1] ]
// generate the permutations
perms = join( @ARGS = list([1:4]) > { [1:4].list } ) :: {
#set($.item) == #$.item
}
// from the templates, get the permutations which can be used for
// generating the input argument for the join
args = list ( my_template ) > {
matching_rows( $.item , perms )
}
// finally join the options to solve the sudoku as a join problem
results = join ( @ARGS = args ) :: {
valid_sudoku ( $.item , 3 )
}
println( results )
// and it is still less than 42 lines of code.

NoOne
November 15, 2016 This is so obvious that comments are really not needed.
// ZoomBA
def sanitize( range ){
#(l,r) = range.split('')
return ( l == r ? l : range )
}
def split_range( range , n ){
#(l,r) = range.split('')
if ( n == l ){
return sanitize( str( int(l) + 1 ) + '' + r )
}
if ( n == r ){
return sanitize ( l + '' + str( int(r)  1 ) )
}
[ sanitize(l + '' + ( n  1) ) , sanitize( str(n+1) + '' + r ) ]
}
def do_fancy_stuff( l ){
fold ( l , list( '099' ) ) >{
res = split_range ( $.prev[1] , $.item )
$.prev.remove( #$.prev  1 )
$.prev += res // cool ?
}
}
println( do_fancy_stuff( [ 0,1,2,50,52,75 ] ) )

NoOne
November 14, 2016 /*
Everyone solved it right.
Thus, I am flexing some muscle power of ZoomBA,
to showcase the full declarative nature of the language :
*/
def find_pivot_index( arr ){
if ( empty(arr) ) return 1
if ( size(arr) == 1 ) return 0
sums = [ 0 , sum( arr )  arr[0] ]
x = index ( [ 1 : #arr ] ) :: {
sums.0 += arr[ $.item  1]
sums.1 = arr[ $.item ]
sums.0 == sums.1
}
x < 0 ? x : x + 1
}
println ( find_pivot_index( [ 0,6,4,1,2,3 ] ) )

NoOne
November 11, 2016 gekko is correct, it is meaningless. But..
In any case, given this json :
{
"value" : 1 , "children" : [
{ "value" : 2 , "children" : [
{ "value" : 4 , "children" : [] },
{ "value" : 5 , "children" : [] }
] } ,
{ "value" : 3 , "children" : [
{ "value" : 6 , "children" : [] },
{ "value" : 7 , "children" : [] }
] }
]
}
This code is going to work out well for the reverse God knows what level order thing:
/*
A Level order traversal.
The key is to understand that,
you need to maintain two queues, one for current,
another for next level.
After a level is exhausted,
one needs to replace that queue by the one from built up.
As we can see, this won't solve Amazon's problem,
Which is a reverse level order traversal.
So, we need to use a stack to store the per level nodes
which are to be stored in a queue! Thus,
The solution becomes , storing the queue in a stack!
But then, who needs queues? We can simply use a list!
*/
def reverse_level_order( root ){
cur = list( root ) // current level
stack = list() ; stack.push( list( cur ) )
while ( !empty(cur) ){
next = list()
for ( node : cur ){
for ( child : node.children ){
next += child
}
}
// push the level into the stack
stack.push ( list( next) )
cur = next
}
// now unwind the stack
while ( !empty(stack) ){
level = stack.pop()
for ( node : level ){
printf( ' %s ' , node.value )
}
}
println()
}
// call it
reverse_level_order( json( 'tree.json' ,true ) )
I am using imperative paradigm  to ensure that it stays comprehensible.
 NoOne November 10, 2016/* ZoomBA.
Level order traversal.
The key is to understand that,
you need to maintain two queues, one for current,
another for next level.
After a level is exhausted,
one needs to replace that queue by the one from built up
*/
def level_order( root ){
cur = list( root ) // current level
while ( !empty(cur) ){
// get one and go along with it
node = cur.dequeue()
printf(' %s ', node.value ) // print it
next = list()
for ( child : node.children ){
next.enqueue( child ) // queue it
}
println() // completes the level
cur = next // switch the level
}
}

NoOne
November 08, 2016 // ZoomBA
def all_comb_words( string ){
len = #string
words = fold ( [ 0: 2 ** len ] , set() ) > {
s = str( $.o,2)
s = ('0' ** ( len  #s ) + s )
opt = fold ( s.value , '' ) > {
$.p += ( $.o == _'1' ? string[ $.i ] : '' ) }
opt = str(opt) ; sorta(opt.value)
$.p += opt
}
println( words )
}
all_comb_words ( 'aabcc' )

NoOne
November 08, 2016 /* ZoomBA.
Observe the problem can be solved fully declaratively.
Observe we can index the chars from the
1. first string as : 0,1,2,3,4...
2. second string as : 1,2,3,...
Now, join with condition:
all ve should be sorted descending
all +ve should be sorted ascending .
then, map back to generate the merged string
*/
def merge_strings( s1, s2 ){
r1 = [ 0 : #s1 ]
r2 = [ 1 : #s2  1: 1]
l = r1.list + r2.list
join_args = list( [0:#l] ) > { l }
join ( @ARGS = join_args ) :: {
// must be unique
continue( #set($.o) != #$.o )
#(pos,neg) = partition( $.o ) :: { $.o >= 0 }
// sorted ascending? if previous > current then it is not
last = reduce( pos ) > { break( $.p > $.o ){ null } ; $.o }
continue ( last == null )
// sorted descending? if previous < current then it is not
last = reduce( neg ) > { break( $.p < $.o ){ null } ; $.o }
continue ( last == null )
// now map back the string as word
true } > { fold( $.o , '' ) > {
$.p += ( $.o >= 0 ? s1[ $.o ] : s2[ $.o  1] ) }
}
}
println( merge_strings( 'hey', 'sam' ) )

NoOne
November 04, 2016 /*
ZoomBA : Using Level Order Traversal
stackoverflow.com/questions/1894846/printingbfsbinarytreeinlevelorderwithspecificformatting
*/
def traverse(rootnode){
thislevel = list( rootnode )
height = 1
while ( !empty( thislevel ) ){
nextlevel = fold( thislevel , list() ) >
$.p += list( $.o.children )>{ $.o }
}
thislevel = nextlevel
height += 1
}
height
}

NoOne
November 03, 2016 /* ZoomBA : with Join */
A = ['a':'z'].string
def decode(string){
len = #string
join_args = fold( [ 0:len ] , list() ) > {
inx = int ( string[$.o] )
continue( inx == 0 )
options = list('')
options += A[inx1]
if ( $.o + 1 < len ){
inx = int( str(string[$.o]) + string[$.o + 1] )
if ( inx < 27 ){ options += A[inx1] }
}
$.p.add ( options ) ; $.p
}
join( @ARGS = join_args ) :: {
w = str($.o,'')
str( w.value ,'' ) > { $.o  96 } == string
} > { str($.o,'') }
}
ip = '1123'
words = decode(ip)
println( words )

NoOne
November 02, 2016 And we have Quora.
quora.com/Youhave1000winebottlesoneofwhichispoisonedYouwanttodeterminewhichbottleispoisonedbyfeedingthewinestotheratsThepoisonedwinetakesonehourtoworkHowmanyratsarenecessarytofindthepoisonedbottleinonehour
Open Chat in New Window
This is what should be done ( ZoomBA )
 NoOne January 12, 2017