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
/*
look and say sequence
en.wikipedia.org/wiki/Lookandsay_sequence
*/
def look_and_say_next( cur_no ){
digits = str( cur_no ).toCharArray
count = 1
buf = ""
past_digit = digits[0]
for ( inx : [1:size(digits)] ){
cur_digit = digits[ inx ]
if ( cur_digit != past_digit ){
buf += ( str( count ) + str( past_digit) )
past_digit = cur_digit
count = 1
} else {
count += 1
}
}
buf += ( str( count ) + str( past_digit) )
int( buf )
}
las = list( 1 )
for ( inx : [0:10 ] ){
next = look_and_say_next( las[1] )
las += next
println( next )
}

NoOne
April 18, 2019 /* LIS */
def lis( input ){
if ( empty(input) ) return []
stacks = list( )
stacks.add( list( input[0] ) )
for ( inx : [1:size( input) ]){
added = false
for ( s : stacks ){
continue ( input[inx] <= s[0] ){
added = true
s += input[inx]
}
}
if ( !added ){ stacks.add( list( input[inx] ) ) }
}
println( size( stacks) )
// top elements of the stacks from left to right
// is the increasing sequence
println( str( stacks , ",") as { $.o[0] } )
}
a = [10, 22, 9, 33, 21, 50, 41, 60, 80]
lis( a )

NoOne
April 18, 2019 /* LIS */
def lis( input ){
if ( empty(input) ) return []
stacks = list( )
stacks.add( list( input[0] ) )
for ( inx : [1:size( input) ]){
added = false
for ( s : stacks ){
continue ( input[inx] <= s[0] ){
added = true
s += input[inx]
}
}
if ( !added ){ stacks.add( list( input[inx] ) ) }
}
println( size( stacks) )
// top elements of the stacks from left to right
// is the increasing sequence
println( str( stacks , ",") as { $.o[0] } )
}
a = [10, 22, 9, 33, 21, 50, 41, 60, 80]
lis( a )

NoOne
April 18, 2019 /*
Too much convolution in all the answers
Actual, things can be done much faster
*/
def UserActivity : {
user_id : "userid" ,
actions_at : [/* list of timestamps */ ]
}
def PageActivityForDay : {
page_id : "pageid" ,
day : "YYYMMdd" ,
user_activity : { /* map of User Activities keyed by userid */ }
}
// which pages has exactly 100 users in a day?
yo = select( list_of_page_activities_per_day ) where { size( $.user_activity ) == 100 }
// Which page was visited by only one user exactly 15 times in a day?
meh = select( list_of_page_activities_per_day ) where {
exists ( $.user_activity ) where { size( $.actions_at ) == 15 }
}
// Which page was visited by u3 more than 20 times in a day?
foo = select( list_of_page_activities_per_day ) where {
"u3" @ $.user_activity && size( $.user_activity["u3"].actions_at ) > 20
}

NoOne
April 17, 2019 Nearly optimal:
def merge_list_of_list( list_of_lists ){
iterators = list( list_of_lists ) as { $.o.iterator }
final_merge_list = list( )
added = true
while ( added ){
added = false
for ( it : iterators ){
added = it.hasNext
if ( added ){
final_merge_list += it.next // done
}
}
}
final_merge_list // return
}

NoOne
April 17, 2019 /*
In the current form, the question is ill posed.
It is as good as asking, given an array, find which indices
the maximal elements are  and return one at random.
More realistic and proper question would be:
Given a stream of integers, at any given time, if we were to ask
Give me a random index where the maximal element has appeared.
That would be worth interesting effort.
So we start.
*/
def bucket : { val : num('inf'), indices : list(1), cur_index : 1 }
def find_random_index( integer_iterator , bucket ){
if ( integer_iterator.hasNext ){
bucket.cur_index += 1
next_int = integer_iterator.next()
if ( next_int > bucket.val ){
bucket.val = next_int
bucket.indices = list( bucket.cur_index )
} else if ( next_int == bucket.val ){
bucket.indices += bucket.cur_index
}
}
random( bucket.indices ) // return a random value from collection
}

NoOne
April 12, 2019 Never reinvent the wheel. You are in Darwin, and you should simply use:
[ stackoverflow.com/questions/6637882/howcaniusegreptoshowjustfilenamesnoinlinematchesonlinux/6637894 ]
And yes, you can simply use grep.
[ digitalocean.com/community/tutorials/usinggrepregularexpressionstosearchfortextpatternsinlinux ]
Thus, the solution is really using regex in grep with "l" option.
/*
Observe the problem of cartesian product from arbitrary no.
of lists. Suppose the lists are : L1, L2, L3, ... Ln
with sizes s1, s2, s3, .. sn
Let the element in the i'th position of k'th list is Lk[i].
The configuration of such indices at any point is, then :
0 0 0 0 ... 0 // n times for the first tuple
0 0 0 0 ....1 // for the 2nd tuple...
...
0 0 0 0 ....(sn1) // for the sn Tuple.
After than, the first column will be reset, and carry will be generated,
so that the next tuple will be:
0 0 0 0 ...1 0 // for the ( sn + 1) Tuple.
Thus, generating next tuple's index is generating the carry, if any,
and resetting the indices from the index which generated the carry to the end,
and incrementing the index of the left one. This again can generate carry,
so it is a ripple effect from rightmost side to the left most side.
Thus, hasNext() is always possible, till the leftmost list is not exhausted by carry.
next() is the tricky one, where we need to define the carry and the ripple from right to left.
When there is no carry, we can stop having the ripple.
*/
def inc_iterator( some_list, cur_iterator ){
if ( cur_iterator.hasNext ){
return [ false , cur_iterator ]
} else {
return [ true, some_list.iterator ]
}
}
def cartesian ( list_of_list ){
iterators = list ( list_of_list ) as { $.o.iterator } // get the iterators
my_tuple = select( iterators ) where { $.o.hasNext() } as { $.o.next() }
if ( size( my_tuple) < size(list_of_list) ) return [] // empty tuple
println( my_tuple )
carry = false
while ( !carry ){
for ( i : [ size(list_of_list)  1 : 1 ] ){
#(carry,iter) = inc_iterator( list_of_list[i], iterators[i] )
if ( i == 0 && carry ) { return } // because now I am having carry to the left
iterators[i] = iter
my_tuple[i] = iter.next
break ( i != 0 && !carry )
}
println( my_tuple )
}
}
cartesian ( [ ['a','b', 'c'] , ['p', 'q' ], ['r','s' ] ] )

NoOne
March 11, 2018 There is no middle of anything when we are looking at a number. A number, rather more precisely integer is given by this regex (ignoring sign) :
N > [09]+
That would mean, in a context free way, it can be written as :
N > [09]* [09]? [09]*
That is how you should define middle. In this definition, of course middle becomes meaningless. Example: 34543 . What is the middle? My grammar of course is terribly ambiguous, but hope I did make the point.
Now, of course there are two problems.
1. Get all the factors of a number. This is not very interesting problem.
[ geeksforgeeks.org/finddivisorsnaturalnumberset1/ ]
2. A predicate to declare if a number is a special number. That is slightly more interesting.
But then fairly trivially done by (with proper collection minus and subset definition ):
special_digits = '356'.toCharArray
all_digits = ['0':'9'].string.toCharArray
drop_digits = all_digits  special_digits
def is_special_no( n ){
// set minus : to get the left over digits after subtracting drop_digits
left = set ( str(n).toCharArray )  drop_digits
// when left is non empty and is a proper subset of special_digits then true
!empty(left) && left <= special_digits
}
println( is_special_no(104) )
But the bigger question is, why write this way? It is terribly unoptimal !Clearly there are better way to do so? As it turned out, there is!!
special_digits = set ( '356'.toCharArray )
def is_special_no( n ){
!empty ( select ( str( n ).toCharArray ) where { $.o @ special_digits } )
}
println( is_special_no(134) )
Now this is cleaner, neater, and optimal. Now it is trivial to generate the appropriate imperative code.
 NoOne March 07, 2018This is terribly language specific question. In fact I would go to the point saying it is a non question for anything above C. In C++ we already have arbitrary precision integers.
[ stackoverflow.com/questions/2568446/thebestcrossplatformportablearbitraryprecisionmathlibrary ]
In a slightly better human/declarative language  this is as cakewalk as :
sum ( file( 'input.txt' ) ) as { int( $.o ) } // this is ZoomBA
sum(int(v) for v in open('input.txt') ) # Python
Now, same in Java is actually left as exercise.
 NoOne March 07, 2018/* A naive solution is mark the time index and increment.
When we add a [start,end] we add and mark all time slices
between these  but terrible usage of memory : call it version 1
*/
def mark_and_inc( history, log_slice ){
for ( t = log_slice.start ; t <= log_slice.end ; t+= 1 ){
if ( t !@ history ){
history[t] = 0
}
history[t] +=1
}
}
// create history by repeating mark and add
def create_history( logs ){
history = dict()
for ( l : logs ){
mark_and_inc( history, l)
}
history // return
}
// create history
history = create_history( logs )
// query is as straight forward as
def process_count_at( t ){
t @ history ? history[t] : 0
}

NoOne
March 05, 2018 /*
Observe that the problem is that of finding locations where
we can cut the string.
Given a string of length 's' has exact s1 locations where we can cut it
That s1 becomes the number of choices = n.
Clearly then the number of comma = k is the cut locations to be selected.
It is obvious that the order in which the cut was imposed does not matter.
Thus, the choices are C(n,k).
Thus, the problem is:
1. finding combinations of cut
2. Applying the cuts
3. Maintaining a max out of the cuts
*/
def do_fancy(string, k){
n = size(string)  1
range = [0:k+1]
max = 0
for ( t : comb(range,k) ){
start_inx = 0
words = list()
for ( i = 0; i < k ; i+= 1 ){
words += int( string[start_inx:t[i]] )
start_inx = t[i] + 1
}
words += int( string[start_inx:1] )
#(m,M) = minmax( words )
#(m,max) = minmax( max, M )
}
max // return
}
println( do_fancy( '89769957',3 ) )

NoOne
February 09, 2018 /*
Makarand is right.
The best way to handle it is O(nk), where:
n is the size of the dictionary
k is the average size of the words in the dictionary by unique characters
Observe the use of counter, what we are trying to do is multiset.
en.wikipedia.org/wiki/Multiset
Given zoomba defaults into multiset using mset()
and let's set operation ( subset ) over multisets
The problem becomes trivial code.
== Appendix : Multiset Subset Operation ==
Given a list/sequence, a multiset is M = { (key,count) }
Now, M1 is subset of M2, if and only if :
for all key in M1,
1. key exists in M2
2. count of key in M1 <= count of key in M2
==
And now the solution
*/
// step 1, load dictionary and make each entry multiset :: one time
md = list ( file('/BigPackages/words.txt') ) as { [ $.o, mset( $.o.toCharArray ) ] }
// get input word
input_word = 'makarand'
test_word = mset( input_word.toCharArray )
// where each word in md is a subset ( multiset sense ) of test_word O(n*k)
subset_words = select ( md ) where { $.o.1 <= test_word } as { $.o.0 }
// we are done
println( subset_words )
Yielding:
[ a,aa,aaa,aam,ad,adam,adar,adm,adman,ak,aka,akan,akra,am,ama,amadan,amar,amarna,amra,an,ana,anam,anama,and,anda,ankara,ar,ara,arad,arak,arank,ark,arm,armada,arn,arna,d,da,dak,dam,dama,daman,damar,damn,dan,dana,dank,dar,dark,darn,dk,dkm,dm,dn,dr,dram,drama,drank,,k,ka,kaama,kam,kama,kan,kana,kanara,kand,karanda,karma,karn,km,kn,knar,kr,kra,krama,kran,krna,m,ma,maad,maana,maar,mad,makar,makara,makran,man,mana,manada,manak,mand,mandar,mandra,mank,mar,mara,mark,marka,md,mk,mn,mna,mr,n,na,naa,naam,nad,nada,nak,nam,namda,nar,nard,nark,nd,nm,nr,r,ra,raad,rad,rada,radman,rakan,ram,ramada,ramadan,ran,rana,rand,rank,rd,rm,rn,rnd, ]

NoOne
October 22, 2017 /*
Step 1: Pick 5 numbers from 1...52. That is al combinations of C(52,5)
achivable using comb([1:53],5)
Now, pick any of these 4 ops [ +,,*,/] on these 5 numbers.
Use floating point to be exact
Each permutation has then 4^4 ways of assigning operators.
stringify it, do an eval.
Check it out if result is 42
*/
__OPS__ = { _'0' : '+' , _'1' : '' , _'2' : '*' , _'3' : '/' }
def do_facebook(){
total_ops = 4 ** 4
// create the operator varities
ops = list()
for ( k : [0:total_ops] ){
s = str(k,4)
s = '0' ** (4  size(s)) + s // left pad by '0'
ops += s
}
// select tuple from C(52,5) :: for demo.. we have to 8
for ( nums : comb( [1:8] , 5 ) ){
// select operators....
for ( op : ops ){
s = ''
for ( i = 0; i < 4; i+= 1 ){
s += ( str(nums[i]) + '.0' + __OPS__[ op[i] ] )
}
s += ( str(nums[4]) + '.0' )
// do eval ?
x = #'#{s}' // yes
if ( x == 42.0 ) {
// the answer to life, universe and everything...
println(s)
}
}
}
}
do_facebook()
Yields...
=====
1.0*3.0*4.0+5.0*6.0
1.0/2.0*3.0*4.0*7.0
1.0+2.0*3.0+5.0*7.0
1.0+2.0+4.0+5.0*7.0
1.0*3.0+4.0+5.0*7.0
1.0+2.03.0+6.0*7.0
1.0+2.0*4.0*6.07.0
1.0+3.04.0+6.0*7.0
2.0+3.0+5.0*6.0+7.0
2.0+3.05.0+6.0*7.0
1.0+4.0+5.0*6.0+7.0
1.0+4.05.0+6.0*7.0
=====
Analysis.
The problem is that of :
1 + 3 + 5 + ...
That is sum of n odd numbers.
That is known to be : 9math.com/book/sumfirstnoddnaturalnumbers
=> n^2.
Thus we are to find, if the number given is a perfectly square no. or not.
Now, given we do not want to use square root, which is
a terribly complex operation, we can do as follows:
[ careercup.com/question?id=14797683 ]
@milincjoshi :
You do not need to do recursion at all, to solve this sort of problem. Observe that the problem can be partitioned into two unrelated problems.
[1] Given a list of list, find which lists has the exact sum as S.
Now, if you were to think in terms of SQL, that will be :
select from whatever where sum( all columns ) == S
Which is a very neat and easy problem to solve.
[2]
Now, who generates this list of list? That is where the problem lies. The problem says, all possible subsets of a set. Ah. That is a power set. Google it up. There are many ways to generate a list of all possible subsets of a set, and one is clearly through recursion.
But that is the lamest way of doing it, computationally. Here, we can use Ramanujan's method. What is that?
Imagine for every item in the set ( list ) you can choose to take the item, and choose not to take the item. So, if the list is :
{ 1, 3, 4, 5, 6, 15 }.
You can say, for 1, 0 ( not select ) , for 3 : 0, ... for 15 0.
That would be : 00000 > 0.
That selects the subset, empty set.
In the same way :
00001 > 1. selects the subset { 15 }.
So, what did we learn? We learn that iterating over different binary representation of
0 to 2^n where n is the number of items in the list, we can generate a pattern
which can then be used to select the corresponding subset!
That concludes our problem [2]!
Now, anyone can easily solve the problem with much cleaner, and neater code.
def find_median_lazy( a, b ){
s = sset() // sorted set
s += a
s += b
l = list(s) // done, to get indexer up
len = size(l)
if ( len == 0 ) return null
// and now the rest
mid = len/2
if ( len % 2 == 0 ){
// even case, then
return (l[mid1] + l[mid])/2.0
}
return l[mid]
}
println( find_median_lazy( [1,2] , [3,4] ) )
println( find_median_lazy( [1,2,5] , [3,4] ) )
def _merge_(a,b){
l = list()
i_a = 0
l_a = size(a)
i_b = 0
l_b = size(b)
while ( i_a < l_a && i_b < l_b ){
if ( a[i_a] < b[i_b] ){
l += a[i_a]
i_a += 1
} else {
l += b[i_b]
i_b += 1
}
}
while ( i_a < l_a ){
l += a[i_a]
i_a += 1
}
while ( i_b < l_b ){
l += b[i_b]
i_b += 1
}
l // return
}
def find_median_with_unnecessary_work(a,b){
l = _merge_(a,b)
len = size(l)
if ( len == 0 ) return null
// and now the rest
mid = len/2
if ( len % 2 == 0 ){
// even case, then
return (l[mid1] + l[mid])/2.0
}
return l[mid]
}
println( find_median_with_unnecessary_work( [1,2] , [3,4] ) )
println( find_median_with_unnecessary_work( [1,2,5] , [3,4] ) )

NoOne
September 25, 2017 /*
'NORTH' +
'0EAST' +
'0WEST' +
'SOUTH'
===========
'EARTH'
2(H + T) % 10 = H // constraint 1
(2(T + S) + 2(H+T)/5) % 10 = T constraint 2
Solving these two reduces the problem from 10! into 7! Baam.
That is heavily reduced.
Now let's see how H, T, S are there.
*/
def is_valid( map ){
north = map.h + 10 * ( map.t + 10 * ( map.r + 10* ( map.o + 10 * map.n )))
east = map.t + 10 * ( map.s + 10 * ( map.a + 10* ( map.e ) ) )
west = map.t + 10 * ( map.s + 10 * ( map.e + 10* ( map.w ) ) )
south = map.h + 10 * ( map.t + 10 * ( map.u + 10* ( map.o + 10 * map.s ) ) )
earth = map.h + 10 * ( map.t + 10 * ( map.r + 10* ( map.a + 10 * map.e ) ) )
earth == ( north + east + west + south )
}
digits = [0:10].asList
// find constraint 1
c1_pairs = join(digits,digits) where { ($.l != $.r) && ( $.l == 2 * sum($.o) % 10 ) }
// get next set of constrant 2 ?
c2_tuples = join(digits,c1_pairs) where {
#(H,T) = $.r
S = $.l
S !@ $.r && ( ( 2 *( T + S ) + 2*(H+T)/10 ) % 10 == T )
} as { d = { 'h' : $.r.0 , 's' : $.l , 't' : $.r.1 } }
rest_of_lettrers = [ 'a' , 'e' , 'n', 'o', 'r', 'u' ,'w' ]
// now that we have established the 3 items,
// rest 7 has to be chosen who are not ... in the group
for ( t : c2_tuples ) {
other_digits = digits  t.values
// now permuatate the other_digits
for ( p : perm( other_digits ) ){
// assign into map
d = dict( rest_of_lettrers ) as { [ $.o, p[$.i] ] }
d = t // the whole map
if ( is_valid( d ) ){
println( d )
}
}
}
Producing...
{a=1, r=6, s=0, t=8, e=5, u=3, w=7, h=4, n=2, o=9}
{a=2, r=5, s=0, t=8, e=6, u=1, w=7, h=4, n=3, o=9}
{a=3, r=1, s=0, t=8, e=7, u=9, w=2, h=4, n=5, o=6}
{a=3, r=5, s=0, t=8, e=7, u=9, w=2, h=4, n=6, o=1}
{a=0, r=5, s=1, t=6, e=7, u=2, w=4, h=8, n=3, o=9}
{a=3, r=2, s=1, t=6, e=7, u=9, w=4, h=8, n=5, o=0}
{a=3, r=4, s=1, t=6, e=7, u=9, w=0, h=8, n=5, o=2}
{a=9, r=5, s=1, t=6, e=3, u=7, w=4, h=8, n=2, o=0}
{a=9, r=0, s=1, t=6, e=7, u=3, w=2, h=8, n=5, o=4}
{a=3, r=1, s=2, t=5, e=9, u=7, w=6, h=0, n=4, o=8}
{a=4, r=1, s=2, t=5, e=8, u=7, w=6, h=0, n=3, o=9}
{a=7, r=8, s=2, t=5, e=9, u=3, w=4, h=0, n=6, o=1}
{a=8, r=9, s=2, t=5, e=4, u=7, w=6, h=0, n=1, o=3}
{a=8, r=6, s=2, t=5, e=7, u=4, w=1, h=0, n=3, o=9}
{a=9, r=8, s=2, t=5, e=4, u=6, w=7, h=0, n=1, o=3}
{a=9, r=6, s=2, t=5, e=7, u=3, w=8, h=0, n=4, o=1}
{a=9, r=6, s=4, t=1, e=7, u=3, w=0, h=8, n=2, o=5}
{a=2, r=3, s=5, t=8, e=7, u=9, w=1, h=4, n=0, o=6}
{a=2, r=6, s=5, t=8, e=7, u=9, w=3, h=4, n=1, o=0}
{a=2, r=6, s=5, t=8, e=9, u=7, w=1, h=4, n=3, o=0}
{a=3, r=7, s=5, t=8, e=6, u=9, w=1, h=4, n=0, o=2}
{a=6, r=0, s=5, t=8, e=9, u=3, w=1, h=4, n=2, o=7}
{a=7, r=1, s=5, t=8, e=9, u=2, w=6, h=4, n=3, o=0}
{a=9, r=1, s=5, t=8, e=6, u=3, w=7, h=4, n=0, o=2}

NoOne
September 20, 2017 /* The recursive formulation is too easy
So, let's improve on that.
Observe the problem can be recursively formulated
as cardinal product of two lists, left one, is a conjugate
(items themselves may be list), while right ine is a primitive one.
Thus, simple for loop suffices, which then yields the left list
for the next iteration.
*/
def _cross_( conjugate, primitive ){
result = list()
for ( l : conjugate ){
for ( r : primitive ){
// concatenate these lists
row = list(l)
row += r
result.add(row)
}
}
result // return them
}
def cross( arr_of_arr ){
if ( size(arr_of_arr ) <= 0 ) return [] // fixed
cur_index = 0
// generate left list, conjugate
left_list = list ( arr_of_arr[cur_index] ) as { list( $.o ) }
cur_index += 1
while ( cur_index < size(arr_of_arr) ){
left_list = _cross_(left_list,arr_of_arr[cur_index] )
cur_index += 1
}
left_list // return... and we are good
}
// sample test case
a = [ [ 'a' , 'b' ] , [ 'c' , 'd' ] ]
r = cross( a )
println(r)

NoOne
September 16, 2017 // Globals are terribly bad...
// use closure instead
$state = 0
$even = true
def exit(){ $state >= 12 }
def func_0(){
while( !exit() ){
#atomic{
if ( 2 /? $state ){
printf(0)
$state += 1
$even = !$even
}
}
}
}
def func_even(){
n = 0
while( !exit() ){
#atomic{
if ( $state % 2 == 1 && $even ){
n += 2
printf(n)
$state += 1
}
}
}
}
def func_odd(){
n = 1
while( !exit() ){
#atomic{
if ( $state % 2 == 1 && !$even ){
n += 2
printf(n)
$state += 1
}
}
}
}
threads = [ thread() as { func_0() } , thread() as { func_even() } , thread() as { func_odd() } ]
while ( exists( threads ) where { $.o.alive } );
println()

NoOne
September 04, 2017 A graph.
yes. You heard that right. FileSystem is not a tree. Never was. The moment you invented the notion of [ askubuntu.com/questions/108771/whatisthedifferencebetweenahardlinkandasymboliclink ]  tree is dead. Long live the graph.
And we are done.
Well ordering principle suggests that the set of binary trees can actually be ordered, axiomatically. It is well known that the number of possible binary trees given node n, is
n'th Catalan Number : [ en.wikipedia.org/wiki/Catalan_number ].
C[n] is the number of rooted binary trees with n internal nodes (n + 1 leaves or external nodes).
Thus, the problem is about enumerating these configurations given *n* and then picking
one configuration at random.
Now, that means, *with equal probability* implies, a Random binary tree having n nodes,
therein generated must have a probability of 1/C[n] where C[n] is the n'th Catalan number.
In this formulation it is obvious that the problem is beyond trivial.
Unless, they are asking a random walk problem with equal probability
of having a { left node, right node, or both nodes. }, then it is very trivial.
The first problem is here :
[ tristaninterview.blogspot.in/2012/02/enumerateallpossiblebinarytrees.html ]
With the binary counting method, the problem is solved.
Again, the key issue is about the *equal probability*. They are certainly non trivial for non linear
expressions like this.
A pretty neat way is the recursive formulation as such:
def Node{
def $$(value, l=null, r=null){
$.value = value
$.children = [l,r]
}
def s_rep(){ // for string format
r_str = $.children[1] == null ? '' : $.children[1].s_rep()
l_str = $.children[0] == null ? '' : $.children[0].s_rep()
str( '(%s %s %s)', l_str, $.value, r_str )
}
}
// call it off
ll = new ( Node , 10 )
lr = new ( Node , 30 )
l = new ( Node , 100 ,ll, lr )
r = new ( Node , 130 )
root = new ( Node , 42 , l , r ) // root node
println( root.s_rep() )
Which produces :
((( 10 ) 100 ( 30 )) 42 ( 130 ))
From this, it is very easy to parse back into the tree.
The recursive formula of a any tree in this form is :
( ( left_sub_tree_rep ) my_value ( right_sub_tree_rep ) )

NoOne
August 23, 2017 There are at least two ways to solve it with O(n).
1. Sort using radix sort, and then linear search. Solved using Theta(k n ) where k = Log(max(arr),10) or rather any base.
2. The one I am posting down  much complex:
def max_contiguous_sub_seq( my_list ){
left = dict()
right = dict()
for ( x : my_list ){
prev = x  1
next = x + 1
merged = false
if ( prev @ right ){
merged = true
val = right[prev]
val += x
right = prev
right[x] = val
}
if ( next @ left ){
merged = true
val = left[next]
left = next
val.add(0,x)
left[x] = val
}
if ( !merged ){
// here, create one element guy
my_list = list( x )
left[x] = my_list
right[x] = my_list
}
}
// find the max length guy from left/right
#(min,max) = minmax( left ) where { size($.l.value ) < size($.r.value ) }
max.value // here we go
}
l = [ 1, 11, 102, 12, 32, 13, 80, 10 ]
sol = max_contiguous_sub_seq(l)
println(sol)

NoOne
August 22, 2017 The question has problem, the trivial solution is to have a substring with size 1. If we do ignore the substring of size 1, then :
def longest_repeated_substring( string ){
n = size( string )
if ( n <=1 ) return ''
counter = dict()
join ( [0:n], [0:n] ) where {
continue( $.1  $.0 <= 1 ) // when ( j  i > 1 ) for pairs
sub_string = string[$.0:$.1]
if ( sub_string @ counter ){
counter[sub_string] += 1
} else {
counter[sub_string] = 1
}
false // we do not want to add, at all
}
// find min, max
#(min,max) = minmax ( counter ) where { $.l.value < $.r.value }
max.key
}
println( longest_repeated_substring('banana') )

NoOne
August 22, 2017 def solve( my_list ){
// 0 is left partition, 1 is right partition
// a bit pattern of size(my_list) = n signifies the selection
// 0 1 0 1 0 > pick the 0 for left, 1 for right
// 1 2 3 4 5 > left : [1,3,5], right : [2,4]
// this is the bitmap trick
n = size(my_list)
N = 2 ** n
// infinity with null, lame!
min_diff = { 'value' : num('inf') , 'partitions' : null }
for ( my_num : [1:N] ){
string_rep = str(my_num,2) // in binary
// left pad 0
string_rep = '0' ** ( n  size(string_rep) ) + string_rep
// partition them using when 0 comes left, 1 comes right
#(left_items, right_items ) = partition ( [0:n] ) where { string_rep[$.o] == _'0' }
left_sum = sum ( left_items )
right_sum = sum ( right_items )
// this is pretty straight forward
diff = #left_sum  right_sum 
if ( diff < min_diff.value ){
min_diff.value = diff
min_diff.partitions = [ left_items, right_items]
}
}
min_diff // return
}
l = [1,2,3,4,5]
md = solve( l )
println( md )

NoOne
August 21, 2017 def find_node_with_value(root,node_value){
stack = list()
stack.push(root)
while ( !empty(stack) ){
node = stack.pop()
if ( node_value == node.value ){
return node
}
if ( node.left != null ){
stack.push(node.left)
}
if ( node.right != null ){
stack.push(node.right)
}
}
return null
}
// i have an implicit root
def find(x,y){
x_node = find_node_with_value(root ,x)
if ( x_node == null ) return false
y_node = find_node_with_value(x_node ,y)
y_node != null // return this
}

NoOne
August 16, 2017 In pure declarative form, using recursion  which can easily be removed:
def _recurse_(target,path){
if ( target == path[1] ){
println( path )
return
}
diff = target  path[1]
power_options = list([0:diff]) as { break( 2 ** $.o > diff) ; $.o }
for ( pow_2 : power_options ){
new_cur = path[1] + ( 2 ** pow_2 )
_recurse_ ( target, path + new_cur )
}
}
def print_paths(n){
_recurse_(n,[0])
}
print_paths(4)

NoOne
August 10, 2017 A much simpler approach using Java BigIntegers:
/* A clean solution using Java BigInteger.
We need to have N bulbs, so N binary digits we need
To have so, we must have a N+1 size integer.
*/
def Bulbs{
def $$(N){
s = str(2 ** ( N + 1 ))
$.underlying = new ( 'java.math.BigInteger' , s )
}
def is_on(i){
// tutorialspoint.com/java/math/biginteger_testbit.htm
$.underlying.testBit(i)
}
def toggle(start,end){
$.underlying = fold([start:end+1],$.underlying){
// tutorialspoint.com/java/math/biginteger_flipbit.htm
$.p.flipBit($.o)
}
}
}

NoOne
August 10, 2017 For the languages where the choice() function is available, @Fernando's solution is right. To use his solution one needs to :
if __name__ == '__main__':
func = gen_random(4,[2,1])
counter = dict()
for i in range(0,1000):
x = func.next()
if x not in counter:
counter[x] = 0
counter[x] += 1
print (counter)
However, for the languages which does not have a choice function, there is a way too  the precise thing @ahetuki is doing.
 NoOne July 31, 2017@ChrisK, ok now I get it. They want to generalise Rank :
[ people.csail.mit.edu/sanchez/papers/2016.model.hpca.pdf ] something like this.
Given a generic function, that can shuffle the order *completely*  I rather doubt there is any point  unless we specify what sort of property the ranking function has.
@funk :
===
Assuming the tasks need to be run in the order given, as per the example
==
No, not really. This is variant of task scheduling problem, and you can use any permutation of the tasks, such that when applied  the slots are minimal.
That would be the precise formulation.
Open Chat in New Window
 NoOne April 19, 2019