SCB-FM eTrading IV#1

Q: tell me more about your pricing projects
Q: is your project management style agile?
Q: what’s const correctness and “mutable”
Q: cpu cache optimization

(open) Q: forward vs backward iteration of array .. any performance difference?
%%A: i don’t know any, though some people advocate backward

Q: make_shared advantage over calling ctor of shared_ptr?
%%A: memory leak… Correct. See
%%A: one allocation only
%%A: perfect forwarding

Q: is shared_ptr thread safe?
%%A: yes only for the increment of reference count
%%A: if concurrent with a copying operation on inst3, inst3 is reset on another thread, then I don’t know if it’s thread safe. See thread-unsafe shared_ptr: tiny examples

Q5: any experience with c++11?
Q5a: what are the c++11 code modernization changes you described in resume. Examples?

Q: auto_ptr vs unique_ptr
%%A: unique_ptr can be moved (explicitly), not copied. auto_ptr can be copied and moved??
%%A: unique_ptr can go into containers. Yes see unique^shared^auto_ptr #container

LiquidNet IV c++

Q1: partition list into good^bad sections

Q3b: fix a sample source code that passes unique_ptr<int> by value to a foo() function:

unique_ptr<int> foo(unique_ptr<int> kk)

Q3b.1: give examples of move semantic

Q3b.2: write a template solution to check if the template argument T is a pointer type. I don’t have a good solution but I mentioned SFINAE. My github has a sample sfinae code to check for specific types of pointers. In contrast, std::is_pointer doesn’t handle ptr to member etc.

How about static_assert? Yes tested

See post on template type arg validation

Q3a: improve

string & find(list<Person> li, string name){
  for (auto i=li.begin(); i!=li.end(); i++)
    if (*i == name) return i->nickname;
  return "";

%%A: last return will crash due to return-by-ref. If my function’s return value can be empty, then I usually return by pointer
%%A: equality check is dubious. Better be explicit like Person(name) or i->convertToString()
%%A: li.end() can be cached
%%A: ++i
%%A: li and name should really be const ref

Q4: predict output
%%A: I feel #2/3 are bad code but compiler may not be able to

struct B{void foo(){cout<<"hello\n";}; b = new B(); b->foo(); //#1
delete b;
b->foo(); //#2 .. what?
b->foo(); //#3 .. what?

buggy RAII-powered smart_ptr #SIG

Q1: given a well-behaved class X, someone wrote a RAII wrapper below. What problems do you see?

Q1b: how would you fix them?

%%A1: memory leak of x1, due to the synthesized op=()
%%A1: double-delete on x2

Q1c: OK Good. Now what if X has subclass Y,  all with virtual dtor?
%%A1c: X and Y each create virtual clone() to return a pointer to the host type

Q2: what’s the outcome of double-delete?
AA: undefined behavior. You are lucky if it crashes.

struct A{
  A(X* x): myX_(x){}
  ~A(){delete myX_;}
  X* myX_;
void demo(){
  A a1(new X()); //unnamed x1 object on heap
  A a2(new X()); //unnamed x2 object on heap
  a1 = a2;
/////////// above is original code; below is my Q1b answer -- Add op=()
A & operator=(A const & rhs){
  if (this != &rhs){
    auto tmp = this->myX_; //delete only after successful "new"
    this->myX_ = new X(*rhs.myX_); //clone the X object of rhs
    // if new or ctor throws, the memory is not really allocated 🙂
    delete tmp; //let's assume no exception here.
  return *this;

CVA c++ IV 2 #oq

void func(ResourceMgr & rm){ 
  int connId = rm.getConn();
  double d=externalFunc(connId); 
  rm.reclaim(connId); //release the resource to the mgr
  • Q5: In the code above, external func can throw, so write a RAII wrapper to prevent resource leak.
  • Q5b: what if you aren’t allowed to use RAII? Ok you said catch-all. Is an empty catch block enough?
    AA: need to re-throw the original exception, to mimic the RAII behavior.
  • Q(paper coding): Iterate over two vectors in lock steps. Which is faster — iterator vs vector index?
  • Q (bond math): Is there any uncertainty in the present value calc on an pre-existing vanilla IRS?
  • q: what design patterns do you use?
  • q: write a singleton skeleton
  • Q: how do we make a class “final” in pre-c++11
    %%A: either make dtor private or make all constructors private
  • Q: is shared_ptr thread safe?
  • Q: any difference — const shared_ptr<T> vs shared_ptr<const T>?
  • %%Q: does it make sense to pass a shared_ptr by const reference? I feel it’s cleaner to pass by raw ptr
    AA!: pass by const-reference is faster and recommended


  • Q: why use weak_ptr instead of raw ptr. Valid question.
    A: See [[std c++lib]] P84.
    A: See last paragraph in
  • Q: you said atomic<int> operator++ probably wraps a CAS in a while loop internally, so is it spinlock?
    %%A: I think so. is a detailed explanation
  • Q34: various synchronization techniques?
  • Q34b: what’s the c++ function to force a memory barrier?
    A: std::atomic_thread_fence(),
    but i feel if an application (not a library) uses this function then something is seriously wrong.
  • Q: can we implement a mutex using CAS?
    AA: blockingMutex implementation ] kernel
    AA: spinlock, not blockingMutex, can be implemented as in
  • ? Q (paper coding): write a piecewise linear interpolation Curve class with a ctor taking a vector<pair<double, double>>.  See
  • Q: What are r-values and r-value references
  • Q: Explain your use of SFINAE. See
  • Q: what’s the c++ library function for cmpxch?
    A: atomic::compare_exchange_weak()
  • Q: is your barcap vol surface used for EOD risk only?
    %%A: no. A trader might suspect a lesser known product is currently mis-priced. She could confirm the live bid/ask are obvious outliers on the fitted surface.
    %%A: a dealer desk price new deals based on the fitted surface, whether or not the strike/expiry requires interpolation.

–Simon Ma:

  • Q (paper coding): implement Fib() recursively and iteratively
  • Q: what’s inline?
  • Q: semaphore vs mutex
  • Q: how did you compute greeks like gamma?
  • Q (bond math): given 6M spot IR = 5% and 12M = 10%, what’s the 6M rate 6M forward?
  • Q: Assign first half of a vector to another vector
    %%A: vector::assign() probably takes two iterators so I can pass v.begin(), v.begin()+5
  • Q (obscure): What data structure to represent a directed graph of N nodes? See NxN matrix for graph of N nodes
    %%A: create a Node class with a single ptr field…
  • Q: use parallel algorithm to compute sum of a vector<int>
    %%A: only the last stage global aggregation has a shared mutable that needs protection. The sub-aggregation can be single-threaded.
  • Q (probability problem): Both Alan and Bob agree to show up at Cafe9 sometime between 12 and 2pm. Whoever arrives first would wait for 15 minutes only. What’s the probability of them actually meeting
  • Q: what’s thread_local?
    %%A (correct): a new storage class that’s similar to static
  • Q (paper coding): A natural number is Good if it is a product of only 3, 5 and 7. The smallest Good numbers are 1,3,5,7,9,15,21,25,27,35… Write a print(int N) to print the Nth Good number. Hint: write a isGood(int k). See
  • Q (unclear): implement subtract(int a, int b) using only operator+ and comparison operators. I feel this question is unclear. Can we use bitwise? Can we multiply?
    %%A: just try all the integers (i) one by one a == b+i
  • Q (obscure): what operators can’t be overloaded?
    %%A: q(?:) correct
    AA: address-of CAN be overloaded!

–Mikhail the mgr

  • Q: inserting 1000,000 items into a list vs a vector without reserve()
    A: vector wins
  • Q: do you define your exception classes?
  • Q: in what context is a deque completely unusable whereas vector is perfectly fine?
    A: a C function taking an array (i.e. a ptr + a count). Vector::data() is designed for this. In Pre-c++11, we can pass &v[0] and v.size()
    A: if the code takes one element and uses pointer increment to access other elements. Deque would fail at segment boundaries.
  • Q89 (coding question): given a vector of T [passed in by const ref], write a template function to return [by const reference] the minimum element.
  • Q89b: how do you handle an empty vector?
  • ? Q89c (obscure): given q(vector const & vec), what can you say about q{auto it = vec.begin()} versus q{vector::const_iterator it=vec.begin()}

SIG phone round

See retrans questions on retrans biz logic if I were CTO

Q: how do you extract the seq number from packet header?
A: reinterpret_cast to a pktHeaderStruct ptr, then read the field

Q: is reinterpret_cast safe?

Q: why is RBTree sometimes faster than hashtable for a small collection? See unordered_map^map performance: unpredictable

Q4: speed of std::sort() on a vector vs list::sort
%%A: probably vector due to cache efficiency
A: also the stability of list::sort comes at a cost

Q4b: how are the two sorting implemented?
%%A: possibly two variations of quicksort

Q: std::sort() vs qsort() in C. Same algorithm, but which is faster?
%%A: std::sort, due to functor inlining
AA: Item 46 in [[effectiveSTL]]

Q: given a csv file with a million rows, you use c/java/c#/py to (convert to number) sum up 2nd column and produce a single output number, which language is fastest?
%%A: main cost is file read, but let’s suppose entire file is loaded into memory.
%%A: I feel python bytecode (even optimized) will be slightly slower. Java (due to JIT) and C are likely faster.
A: now in hindsight I feel integer parsing will cost much more than arithmetics.

CVA c++IV 1

Q: when would you pass (in/out of functions) by ptr rather than non-const ref?
%%A: if the argument can be null, or void ptr
A: if I need to pass a double ptr
A: if I need to pass a raw array
%%A: A factory often returns by ptr or smart ptr, seldom by reference

Q: do you catch exception by value, ptr or reference?
A: slicing

Q: iterating vector by int index vs iterator… which is faster?
A: iterator wins since vec[i] needs a O(1) pointer arithmetic operation to locate the element

Coding question

mvea phone IV c++

Q: any experience with FIX?
Q: how many percent of your time is on support vs development?
Q: are you involved in requirement gathering and analysis?
Q: in your project, where do you use python vs c++?
Q: describe the reliability/resilience features in your NYSE system
%%A: retransmission; hot standby; database dump/restore;
%%A: after a mid-day restart, parser would request replay or snapshot to get up to date with the live feed

Q: What’s “pure virtual” vs virtual?
Q: what’s polymorphism
Q: why do you use smart pointers?
Q: what c++11 features did you use?
Q: what’s the “auto” keyword?
Q: j4 stored proc? See
Q: std::vector vs std::list
%%A: list offers efficient splice, insert/delete in the middle and front. Never reallocates.

Up to 700,000 orders received. Half of them are latency sensitive. System validates each order and generates a “principal order” to be sent out to all the stock exchanges in the U.S. (and sometimes Americas), in FIX. These principal trades provide perfect hedging to MS.

Each of the 700,00 orders look just like a regular cash equity order, except a flag to indicate it’s a OTC swap..

Trex QnA IV #std::forward,noexcept

Q: how would a tcp consumer-client know the server process died rather than a quiet server?

Q: how would a tcp producer-server know a client process died? Signal?

Q: What’s perfect forwarding?

Q: std::forward() vs std::move()? See std::move=unconditional-cast #forward=conditional-cast

Q1: in c++03, a myVectorOfTrade.push_back( Trade(22, 0.7) ) uses how many ctor/dtor invocations?
A: regular ctor, copy-ctor, dtor of the temporary

Q1b: how about c++11?
A: regular ctor, mv-ctor, dtor of temporary. See P293…. We assume there’s a Trade mv-ctor and there’a some pointer field in Trade, otherwise the mv-ctor has nothing to steal and is probably same as copy-ctor

Q1c: what about something like emplace_back(22, 0.7)
A: in-place ctor using placement-new. P294 [[eff modern c++]] perfect forwarding eliminates temporaries is my illustration.

Q: how would “noexcept” improve runtime performance?
AA: P 91 [[effModernC++]] has a short paragraph explaining “noexcept” functions are more compiler-optimizable
AA: P 25 [[c++stdLib]] says noexcept functions don’t require stack unwinding.

Q: please implement a simple Stack class backed by a vector. Implement push(), pop(), top().


Bbg QnA IV

Q: how would you write your own program to see if local system is big-endian or little-endian.

Q2: what design patterns do you use?
A: factory, template-method are used a lot in my code.
A: producer-consumer is an essential pattern in async designs
A: adapter — wrapper functions?
A: When needed, I use visitor as a big gun.

Q2b: you said template method is often used implicitly. Can you give some examples in STL?
A: would be hard since classic template method uses virtual functions but there are very few of them in STL. std::sort() fixes the procedure and let user specify the comparison, using template techniques instead of virtual

Q: how would you design multicast to a number of registered users?


thesys mgr QnA IV

Q: why do you say look-up can be slower on hash table than RBTree?
A: hash collision; slow hashing;

Q: Given a fast parser but a slow disk writer, how do you persist all the messages received?
%%A: socket for IPC
%%A: shared mem is probably faster, even with synchronization cost
%%A: we can also use threads. Now I feel we should use coarse-grained concurrency. Each task is a big chunk of data. One of multiple consumers/writers pick up a chunk and spend a sizable amount of time writing to disk.

Q: what’s your concept of multiplexing?

Q: you notice packet dropping due to overcapacity. What would you do to improve throughput?

Q: what system calls have you used?

bbg-Eq: filters in a screen

Exchanges constantly send you live update messages in a fixed format like

IBM, Price, 100
GOOG, Volume, 5000
MSFT, Volume, 14000
IBM, Price, 99
GS, Volume, 7000
MSFT, Price, 250
GOOG, Price 332

Each message always has exactly 3 fields — ticker, field name, integer value. The value only overwrites the previous value and never aggregates. In this example, the IBM price 99 will wipe out the IBM price 100.

There are up to 100 distinct field names, but many tickers and very high messaging rate.

Each user has a Screen, which holds a variable number of Filters defined by this user. Each Filter has a fixed format like “Price > 150” or “Volume < 9000”. All the filters need to be applied, to return a list of qualifying tickers. In this example, first filter alone returns a list of tickers {MSFT,GOOG} and 2nd filter alone returns {GS,GOOG}. Applying all filters would reduce the list to {GOOG}

Data feed goes into the server. Server maintains thousands of Screen objects, each for one user. When a new message is received, the server must apply all relevant filters. If out of 3000 screens 500 Screens’ lists get updated, then another module will update those 500 clients. You don’t need to design the interface to clients, data feed, threading.

Requirement: design the data store, the screen and filter.

I will assume 3000 Screens. On average, each Screen has 4 filters, defined by that user. If you assume every incoming message must be go through 3000*4 = 12000 filters, I guess you are probably right.

Can you avoid linear searches when applying filters? To illustrate, suppose all the messages are Price numbers. I maintain an unorder_map<ticker, priceValue>, updated constantly. When server applies a single filter, we start with the survivor list from previous filter. Go through each key/value of the map, and erase each disqualified ticker from survivor list. If I start with N tickers and perform N look-ups we get O(N).

Akhil hinted a reverse sorted map<priceValue, ticker>. I will call it a RBTree. This RBTree must be updated with each message, by erase/insert. Suppose we care only about filter latency, not about update latency. Or suppose we get very few updates but many Screens to applyFilters(), then this RBTree can help. We will use lower_bound followed by backward iteration (for example, Price < 150). This is presumably faster than my simple solution of full hash table iteration.

That’s the first filter. How about second filter? Let’s name the RBTree for the second filter “tree2”.  In my simple solution, I start with the survivor list (of size N) from first filter and look up N times against the hash table of the second filter, without full iteration. With the RBTree, we have a choice

  • if tree2.lower_bound() leaves very few (like 5) tickers to be checked, but the survivor list from first filter is large, then we should convert the survivor list to an unordered_set and drive from filter2.lower_bound()
  • If tree2.lower_bound() leaves many (like 9999) tickers to be checked, then we should drive from the survivor list. The tree2 won’t be used.
  • However, in a RBTree, how many nodes come before a given node is hard to count. This counting requires expensive iteration. so I feel the choice cannot be made at runtime. See RBTree range count #enum,auto

bbg-Eq: longest abbreviation #easier

Given a long word with N non-unique characters, we know there can be 2^N abbreviations (including the original word, and including the empty string).

Requirement: I give you a list of strings and you suspect some of them could be an abbreviation of your word. Find the longest string among them that’s a valid abbreviation. Optimize for time complexity.

I feel this problem appears simple but not easy to complete quickly is my python solution, different from the c++ solution below. Not sure which has more bugs.

I started with string::find() and hit the problem of non-unique characters. Interviewer hinted char-matching — the key point I needed for this type of problem.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

typedef string candidate;

vector<candidate> v{"monkey","aaaaaaaaaaaaaaaaaa", "mamalon", "monk"};
string const haystack{"mamalonkey"};
size_t hsize=haystack.size();

//Tip: can use typdef alias in argument:)
bool lenComp(candidate const & a, candidate const & b){
  return a.size()<=b.size();
ostream & operator<<(ostream & os, vector<candidate> const & c){
  size_t const sz = c.size();
  for (int i=0;i<sz; ++i){
        os<<c[i]<<" ";
  os<<endl; return os; } //single-pass 🙂 

bool check1candate(candidate const & c){ 
  if (c.size() > hsize) return false;

  for(int i=0, h=0; h<hsize; ++h){
        if (c[i] == haystack[h]){
          if (i==c.size()-1) return true;
  return false;
int main(){
  sort(v.begin(), v.end(), lenComp);
  cout<<v; for (int i=v.size()-1; i>=0; --i){
    if (check1candate(v[i])){
        cout<<"winner is "<<v[i];
        return 0;


bbg-FX: in-place array shuffle #splice^evict

Update: In-Place usually requires 1) splice 2) swap.

Requirement: given a list like

{1,2,3,4,  25,29,44,33,  159,139,155,150,  177,176,169,180} which describes four Persons
{id1,id2,..age1,age2, weight1,weight2,…height1,height2,..}

Write a program to output each person’s full attributes like

{1, 25, 139, 177,   2, 29, 129, 176,   3, 24, 135, 169,   4, 33, 140, 180}

Note the number of attributes (in this case 4) is an input parameter to your program. You don’t know (or care about) the name of each attribute. If you are told there are 37 attributes in each person, just output attr1 .. attr37.

Note the input and output sequence are important.

Q (Bonus question): do it in-place without creating a new collection. You can still have a small number of variables in your code.
A: one way to “cheat” is to append each output person to end of the original vector. It will double in size, so we will truncate the first half.
A: I believe I can use the “homeless/displacement” technique.
A: I now feel many in-place array reshuffle can be done in place with a single temp variable but this may not be one of them.
A: how about starting with a linked list? has ..

Wells IV #socket/c++/threading

This is one of the longest tech interviews and one of the most enriching 🙂 even though I don’t “like” all their questions — very academic/theoretical, text-book driven, too low-level to be practical, not testing practical zbs.

Q: Any consistently reliable technique to detect stale order in your book?

Q: what’s your frame size if your tcp/ucp buffers sizes are so large?

Q: experience storing ticks?

—— C++ questions:
Q1: how can you avoid the cost of virtual function?
%%A: enum/switch or CRTP

Q1b: what’s CRTP

Q: what if your copy ctor signature is missing the “const”?
%%A: you can’t pass in temporaries or literal values. Such arguments must pass into “const &” parameter or “const” parameter. Correct.

Q: double delete?

Q: policy class? traits class?

Q: STL binders.. use case?

Q: how many types of smart pointers do you use?

Q: difference between java generics vs c++ templates?
%%A: type erasure. Java Compiler enforces many rules, but bytecode saves no info about the type argument, so we can get strange runtime errors.
%%A: template specialization. Template meta-programming
%%A (accepted): code bloat since each template instantiation is a separate chunk of code in the object file and in memory.
A: I have a dedicated blog post on this.

Q: what’s returned by a std::queue’s dequeue operation when it’s empty?
AA: undefined behavior, so we must check empty() before attempting dequeue. I believe ditto for a std::stack

Q: why template specialization?
%%A: customize behavior for this particular vector since the standard implementation is not suitable.

Q: how do you implement a thread-safe c++singleton
A: not obvious. See concurrent lazy singleton using static-local var

Q12: in a simple function I have
vector v1 = {“a”, “b”}; vector v2 = v1; cout<<….
What happens to the ctor, dtor etc?
A: 2 std::strings constructed on heap, vector constructed on stack; 2nd vector copy-constructed on stack; 2 new strings constructed on heap; vector destructors deletes all four strings
A: the actual char array is allocated only once for each actual value, due to reference counting in the current std::string implementation.

Q12b: you mean it’s interned?

Coding question: implement void remove_spaces(char * s) //modify the s char array in place. See %%efficient removeSpaces(char*) #Wells

—— threading, mostly in java
Q: What are the problems of CAS solutions?
A: too many retries. CAS is optimistic, but if there are too many concurrent writes, then the assumption is invalid.
%%A: missed update? Not a common issue so far.

%%Q: Synchronized keyword usage inside a static method?
AA: you need be explicit about the target object, like synchronized(MyClass.class)

Q21: Name 3 effects of java volatile keyword — Advanced. See 3effects@volatile ] java5.

Q21b: analyze the double-checking singleton implementation.
staticInst = new Student(); // inside synchronized block, this can assign an incomplete object’s address to staticInst variable, which will be visible to an unsynchronized reader. Solution – declare staticInst as volatile static field

—— System programming (ANSI-C) questions
Q: have you used kernel bypass?

Q5: how do you construct a Student object in a memory-mapped-file?
%%A: placement new

Q5b: what if we close the file and map it again in the same process?
%%A: the ptr I got from malloc is now a dangling ptr. Content will be intact, as in Quest

Q5c: what if Student has virtual functions and has a vptr.
%%A: I see no problem.

Q: you mentioned non-blocking TCP send(), so when your send fails, what can you do?
%%A: retry after completing some other tasks.

Q4: why is UDP faster than TCP
%%A: no buffering; smaller envelopes; no initial handshake; no ack;
%%A: perhaps most important for market data — multiple recipient with TCP is very heavy on sender and on network

Q4b: why buffering in tcp?
%%A: resend

Q: can tcp client use bind()?
%%A: bind to a specific client port, rather than a random port

Q6: is there socket buffer overflow in TCP?
A: probably not

Q6b: what if I try to send a big file by TCP, and the receiver’s buffer is full? Will sender care about it? Is that reliable transmission?
A: Aquis sends 100MB file. See no overflow]TCP slow receiver #non-blocking sender

Q: in your ticking risk system, how does the system get notified with new market data?
%%A: we use polling instead of notification. The use case doesn’t require notification.

Q: any network engineering techniques?

Q: what kernel parameters did you tune?


—— Stupid best-practice questions:
Q: what’s the benefit of IOC?

Q: Fitnesse, mock objects

Question on j4 factory. See separate blog post.


Thesys QnA IV

Q: what’s the average O() complexity of insertion sort
AA: N^2 in most implementations — comparison-based, but using contiguous memory. NlogN if using skip list

Q: what’s the average O() complexity of heap sort
AA: NlogN, since it’s comparison-based.

Q: what are the synchronization primitives on the operating systems you know

Q: how many levels of caches are in a typical Intel processor
%%A: at least 3 possibly 4.
AA: some intel processors do have 4 levels

Q: name some IPC mechanisms
%%A: 1) shared mem 2) sockets 3) pipes

–2nd round (Don Bush?)

Q: Requirement: insert into a std::map only if key is absent
AA: the insert() function does that by default! Returns a pair<Iterator-where-inserted, bool-isInserted>. I used this same technique in my handleInputInternal()

Q: if my class Student has a private dtor, will it compile?
%%A: yes it’s possible to define a member function to invoke the dtor on a pointer passed in
%%A: deleting a ptr-to-Student won’t compile. Correct!
AA: have a friend call the dtor!

Q: Any guess why STL stack designer didn’t combine top() and void pop() like in other languages? hint: what if the copy ctor throws?
%%A: it’s more efficient if a function doesn’t need to return anything, so we don’t want to force the pop() users to pay a price for something they don’t need.

Q: do you create your own templates?
A: I should name the SFINAE hack!

Q: any restriction on a non-type template parameter’s type?
%%A: int and bool are common. Pointers are allowed. shows even arrays and ptr-to-functions are allowed.
AA: has to be a discrete type, not a float

%%Q: what’s the usage of this non-type parameter?
A: std::array uses it for the size. It can’t be a ctor argument since if you construct an array on stack the size must be known at compile time.

Q: can you use new-arrays with shared_ptr? I think he wanted vector<shared_ptr>
%%A: if I have a new-array to store somewhere, then I think shared_array or scoped_array
A: how about shared_ptr<vector>?

Q: what if ctor failes in Foo * p = new Foo() // will memory leak?
%%A: i know it’s common practice to throw from ctor…

Q: name some c++11 features you used in your recent projects
%%A: unique_ptr, shared_ptr, auto, unordered_map, initializer list for vector/map

Nomura C++quant IV

Q: vs operaotr[]?
%%A: operator[] throws exception only if you specify a compiler flag like D_GLIBCXX_DEBUG. I think this is correct

Q: given a vector or ints, how would you sort it by abs value?
%%A: free function
%%A: subclass “less” with operator(). body is same as the free function

Q: clustered index vs non-clustered?

Q: inputs to price an equity option?
%%A: 5 inputs: K, S, T, r, dividend rate. I missed “implied volatility”, which is a soft market data derived from a raw market data.

Q: inputs to a mortgage prepayment model (or callable bond)? ….
%%A: Black model to price a callable bond. Inputs include yield, maturity, interest rate, but there’s no strike per-se? I think the implied volatility (in which random process?) is the most important factor and needs to be backed out from some market data

Q: how did you construct your yield curves at Barcap?

Q: what’s local vol
A: the instantaneous volatility is a deterministic function of 2 inputs. Deterministic because there’s no dB … See other blog posts.

Q: zero-volatility spread?

Q: how do you compute OAS?
%%A: I think OAS is a curve.

Q: how about dv01?

Q: duration of a 10Y T-bond vs 10Y muni bond? I answered with the (more “visual”) Macaulay duration, which is slightly different from the (most useful) modified duration

STL+smart_pointer for SQL DTO

Are there any best practice online?

Q1: Say I have a small db table of 10 columns x 100 rows. Keys are
non-unique. To cache it we want to use STL containers. What container?
%%A: multimap or list. unordered_multimap? I may start with a vector, for simplicity. Note if 2 duplicate rows aren’t 100% identical, then multimap will lose data

Q1a: search?
%A: for a map, just lookup using this->find(). For list, iterate using generic find()

Q1c: what if I have a list of keys to search?
%%A: is there an “set_intersect()” algorithm? If none, then I would write my nested iteration. Loop through the target keys, and find() on each.
A: for_each()?

Q1e: how do you hold the 10 col?
%%A: each object in container will have 10 fields. They could be 10 custom data classes or strings, ints, floats. Probably 10 smart pointers for maximum flexibility.

Q1h: what if I have other tables to cache too?
%%A: parametrize the CacheService class. CacheService class will be a wrapper of the vector. There will be other fields beside the vector.

Q1m: how about the data class? Say you have a position table and account table to cache
%%A: either inheritance or template.

TradeWeb c++IV

100% QnA interview. No coding no white-board no ECT no BP no algo no data structure.

System is Multi-threaded VC++/MSSQL.

One technical interviewer only. (The other 2 are behavior interviewers.) He is a director and looks very technical. I have met perhaps 3 to 5 interviewers focused on the fundamentals of a language/compiler. They pick one of 10 important parts of a language (like java, c++ or c#) and try to determine how well a candidate understands the key details and the rationales.

Below, Q’s are questions from this interviewer. A’s are my answers/guesses.

Q1: let’s talk about non-virtual dtor. You said there are problems in deleting a subclass instance via a base class pointer. Show an example.
(Now I think giving a non-trivial example requires non-trivial knowledge.)
A: Eg: subclass holds some resources to be explicitly released (via close() or disconnect()) in its dtor, but in our scenario only the base dtor is called. Subclass dtor is not invoked.

Q1b: if subclass dtor is invoked, does it always run the base dtor?
%%A: Yes guaranteed. See my blogpost.

Q1c: if a subclass dtor is virtual and you delete an instance via a subclass ptr, you said this is good and subclass dtor will run, so is the “virtual” unnecessary? In this case, what’s the difference between virtual dtor  vs non-virtual dtor?
%%A: yes in both cases the subclass dtor runs.  If your system is written such that you delete a subclass instance only via a subclass ptr and never superclass ptr, then drop the “virtual” to improve runtime performance.

Q3: Let’s talk about a static member function sf2() in class Base. If you have a reference to a Base instance, Can you call myInstance.sf2()?
A: yes

Q3b: if Base and Der both have a static method sf2()?
A: subclass sf2 tends to hide Base sf2. Static type of myInstance variable is used to determine which version is used.

Q3c: how about myPtr->sf2()? Obscure details that I don’t want to spend too much time on.
%%A: looks very odd, but if it compiles, then it’s static, never dynamic, binding, since there’s no ‘virtual’. See my code in

Q4: when must you use the pointer “this”? Obscure details that I don’t want to spend too much time on.
%%A: ctor chaining? Actually chaining is supported in c++11 but not using “this”.
A: if there’s a field and a local variable of the same name, I use “this->” to disambiguate. CORRECT:) See
A: in my ctor (or method), i may want to print my address. Yes you can usually do that in the caller afterwards but not always
A (hindsight): Similarly, in my ctor (or method) I may want to conditionally save my address in some container. The conditional logic is not doable after the ctor.
A (hindsight): if I know the host object is in an array, I could do array arithmetic using “this” with precaution.
A: delete this. I have seen people doing it.
A (hindsight): CRTP
A (hindsight): if parent class has a const method m1() and non-const overload m1(), you can cast “this” to call either of them.
A (hindsight): what if inside a method you need to access a parent object field hidden by a host object field? Can you cast “this”? Yes tested but not a “must” use case. Alternative solution is B::nonStaticField
AA: sometimes you must return *this where the return type is HostClass&

Q4b: can you think of an example of using “this” to avoid access violation?

Q4h: why would anyone use ctor chaining? Why not call a common (non-static) setter method s2() from multiple ctors of the same class?
A: that setter has to be non-static!

Q4i: You think ctor should not call a non-static method?
%%A: it can, but I don’t do it. The host object is half-initialized, so the setter method must strictly perform field initialization and nothing else.

Q5: why do people use class templates? Note — Interviewer didn’t ask function templates.
%%A: avoid the cost of virtual functions

Q5b: Let’s look at using both class hierarchy and class templates.
%%A: not a good idea to combine them. STL has probably no virtual functions.

Q5c: Let’s see. You said you have a bunch of “payload” classes PL1/PL2/… and you want to use a container of PL1 and another container of PL2. Ok You said that’s a common use case of class templates unrelated to virtual functions. Suppose the container template requires each payload class to implement a method f2(). If f2 is provided by a base class, wouldn’t it be easier (can be virtual or non-virtual)?
A: If there’s a family of payload classes, like Shape, Rectangle, Square… then I feel it’s best practice to use a container of smart pointers. I think it reduces the risk of slicing, among other benefits.
A: if the payload classes don’t form a family hierarchy, then there is probably some template meta-programming technique to provide a default implementation of f2(). I’m no expert on template meta-programming.

[11] threading,boost IV #Sapient perhaps

Read-guard, write-guard ?

Q: how to test if current thread already holds a target lock?
%%A: Though there might be platform-specific tricks, I think it’s not widely supported. Best to use recursive mutex to bypass the problem.
AA: pthread_self() is a C function (=> non-method) that returns the thread id of the current thread.
AA: has a microsoft specific solution
AA: using this thread::id object a lock can “remember” which thread is holding it. shows a gdb technique, not available at runtime.

Q: Is scoped_lock reentrant by default? Can you make it reentrant?
AA: With a boost recursive mutex, a single thread may lock the same mutex several times and must unlock the mutex the **same-number-of-times**.

AA: pthreads supports it. says — If the mutex type is PTHREAD_MUTEX_RECURSIVE and the mutex is currently owned by the calling thread, the mutex lock count shall be incremented by one and the pthread_mutex_trylock() function shall immediately return success.

Q: Boost supports try_lock()?
AA: yes

Q: Boost supports lockInterruptibly()?
A: probably not, but there’s timed_lock

Q: Boost supports reader/writer locks?
AA: read/write lock in the form of boost::shared_mutex

Q: difference between mutex and condition var?

Q: can you write code to implement “recursive” locking with reader/writer threads?
A: key technique is a bool isHoldingLock(targetlock)

Q: what types of smart pointers did you use and when. What are the differences? I’d like to focus on the fundamentals not the superstructures.

Q: what other boost lib?
%%A: I briefly used boost bind. I believe STL binders are imperfect, and lambdas are superior

Q2: if I want a custom class as a map key?
%%A: must overload the less-than operator

Q2c: what if I can’t change the source code?
%%A: derive from binary_function to get a functor, and pass it to map constructor as the optional type param. However, the new functor only has “operator()” overloaded? I think it will still work, as the function doesn’t have to be named “less()”.
AA: Item 42 [[eff STL]]

%%Q2g: is operator less-than a friend func or a method?
AA: can be a non-friend(if everything public) or a friend class/func.

PIMCO(accrual account`)c++/java/sql IV

Q: (no good answer) You said users sometimes don’t know what they are requesting so their requirements actually don’t make sense. We as developers need good knowledge to discuss with them and solve the problem, not just take their instructions. Give an example where you challenged a user to understand better what she wants and then proposed a solution that better solves her problem.

Q: bond with sinking fund provision?

Q: suppose you bought at $104.5 with the $4.5 premium (or discount), how do you amortize that amount over the remaining 23 years of the bond? I guess the book value changes over time unlike stocks.

Q: compare a stock and a bond on the same company
%%A: coupon payments follow a predetermined schedule, not discretionary
%%A: bond has an end of life
%%A: future cashflow of the bond is known in advance
%%A: creditor vs partial owner, in the event of bankruptcy
A: bonds (esp. long-duration bonds) are more sensitive to interest rate changes

Q: what’s a bullet bond?
AA: Most bonds repay the principal as a single payment at the end of its maturity, which is known as a bullet payment. For this reason, conventional bonds are also known as bullet bonds. Amortizing bonds, on the other hand, repay the principal over a series of payments rather than all at once on the maturity date, so some or all of the periodic payments will consist of both interest and principal.

Q: how would you describe OO to a procedural programming student
%%A: use a real yet simple example like students/projects/grades/classes/labs/semesters/events/teams to illustrate the essential OO features

Q: how would you describe the spring framework?

q: java vs c++ for a concurrency system like a basic consumer/producer design?

q: java vs c++ for hadoop

%%Q: could I say std::transform() is a swiss army knife?

Q: a SAM interface in c++? Makes sense?

q: describe factory method pattern in c++?

q: bridge pattern implemented in pimpl?

q: can you use scoped_ptr or unique_ptr as class fields?
%%a: scoped doesn’t make sense
AA: wrong interpretation of “scope”. It can be a class field!

q: enable_shared_from_this ? I guess this has to do with the common scenario of two shared_ptr “clubs” each thinking it has sole ownership of a raw pointer

q: how do you declare an interface in c++?
%%A: no field. All methods are pure virtual. No ctor but dtor should be virtual

q: if you don’t declare a copy ctor what does the default copy ctor do?
%%A: bit-wise copy

q: can move ctor be synthesized if you don’t declare one?
%%A: some times it can, but I don’t think it’s always possible.
AA: Correct. for some classes, the standard forbids synthesized move ctor

q: what’s martingale
%%a: a process whose expected value at any future time is equal to the last realized or observed value. No drift.

q: what’s hitting time
%%a: expected time the process will hit a certain level

q: what if my join query produces duplicates, and those tables I join are not my table so I can’t redesign them?
%%a: use distinct or order by.
A: now I think it can happen if you select nothing but “gender”

q: what access modifiers can apply to a java interface?
%%a: private and protected doesn’t make sense. If it’s only used within a package and should not be exposed outside, then the default access may do.
AA: correct


One of the less challenging (but not easy) c++ interviews. No coding test.

  • Q: what editors do you use in your current c++ project
  • Q: function returning pointer to a local object — spot the bug and to fix it.
  • Q: implement a simple singleton class.
  • Q: something about overflow in integer data types
  • Q: non-virtual member function inherited by subclass but problematic when you call it on a subclass instance. It can’t access the subclass field
  • Q: spot the memory leak
  • Q: swap 2 integer variables without using a temp variable.
  • Q: implement sqrt(int) without using the math library.

BGC IV – c++ and Java

Q: how do you mark a memory region as always resident?
A: See mlock() : prevent paging ] real time apps

Q: is select() blocking or non-blocking?
A: Yes select() takes a timeout argument to specify the blocking interval!
A: More interestingly, says after select(), you should use read() which normally won’t block.

Q: server uses socket() listen() bind() accept(). How about client side?

Q1: if a producer thread uses select to send packets to 22 receivers via 22 tcp sockets and a single receiver has very low capacity, what would happen? See tcp: one of 3 client-receivers is too slow

Q1b: select() would show that one sender socket as writable or failed?

Q1c: what if producer keeps sending? What happens next?
%%A: the producers function stack will get an error code.  Wrong!

Q1d: what if UDP rather than TCP
%%A: then no error would occur in the producer system. The slow consumer would be left unnoticed.  There’s no flow-control in UDP

%%Q: can a socket specify a wild card for its local port?
%%A: no. Wildcard is only for local IP
Q: fastest IPC method between producer and consumer? OK you said shared memory, so how do you synchronize the producer and consumer?
%%A: use a named sys-V semaphore in the kernel
A: See boos::interprocess documentation. This is a common requirement addressed in boost.

Q: how does the producer/consumer actually use the shared memory?
%%A: memory mapped file

—brain teasers:
Q: Only a 5L and a 3L pail and a running tap. How to get exactly 4L water in the 5L pail?

Q: you are given a bag of coins (like 1c 1c 1c 5c 5c 10c 25c). Tell me whats the smallest exact payment thats impossible. Every payment must be exact. Hint: sort the coins first, then a clever O(1) single-pass will do.
AA: coin problem #all large-enough amounts are decomposable

Q: given a list of integers, find if any pair adds up to 18
%%A: in one pass, build a hashset of brown items i.e. every item processed so far. For every new (i.e green) item, compute the partner, and look for it in the hashset. If not there, then add the green item as a brown item.
AA: is a clever solution.

—whiteboard coding challenge
Q: given a singly linked list with a start node and null-end node, print each node in reverse, without using any “new” implicitly/explicitly
A: reverse the list first (tail recursion or iteratively), then print normally.

Q: Given an arbitrary directed graph where each parent node has 0 to K children, write a function hasCycle() to check for existence of cycle, visiting each node and each edge once only..
%%A: My verbal algorithm — use breadth-first traversal to trace every branch from root to a leaf node. Detect cycle in each branch. But I wonder whether two parent nodes can have the same descendant node.

Whenever we branch out to 2 child branches, duplicate the parent branch, so that each child branch object has a full path from root.

Each branch object could be a (possibly linked[1]) hashset.
[1] for instrumentation.

Q: given a blackbox utility function String convert(String), write a parallelized Collection parellelConvert(Collection theSequence)
Requirement: theSequence need to be maintained. Size of input is preserved Requirement: Out of 100 items in theSequence, #3 and #5 might be identical, but they still need to show up as “converted” in the output
Requirement: converter uses a very slow and expensive remote system, so we don’t want to send it the same string twice.

%%Q: is countdown latch and join() implemented using wait/notify? %%Q: readResolve vs readObject
%%Q: can CMS ever stop the world?
%%Q: CMS is used in which region of the heap?
Q: what if you suspect theres leak?
Q: what can cause mem leak in java?
%%A: registered listeners; static variables pointing to a collection

Q: why is swing memory footprint so bad?
Q: array blocking queue — when would it block?
%%A: I think a circular array is the underlying.

c++SCB eFX IV#Dmitry

100% QQ type, as defined in feel many are micro optimizations with questionable improvement. I wonder how much value such obscure knowledge adds to the team.

Q: Scanning a vector of int (like finding the average or max). Forward iteration vs backward iteration, which one could be faster, considering all possible compiler optimizations.

%%A: forward. Memory read into cpu cache will be in chunks i.e. cachelines, not one element at a time. Easy for forward iteration. Not sure about backward.

Q: Which one could be fastest:

void f(double arg){…..}
void f(double & arg){….}

%%A: inlining for first but not 2nd?
A: See esp. the long answer.

Q: Thr1 and Thr2 on 2 CPU’s both update an object s, having 2 fields. Thr1 only updates s.field1. Thr2 only updates s.field2. No interference. No synchronization required. We observe the performance is slower than using one thread to update both fields. Any explanation?
%%A: caching in cpu

Q: weak_ptr justification, when we have shared_ptr already? I feel [[effModernC++]] has a good chapter on it.

Ashish pointed out in some apps, you could identify a clear risk of circular dependency. Replace with weak_ptr to permit the destruction.

Q: given an 2D array arr[10][5], how do you use pointer arithmetic to hit arr[1][5]

A: Contiguous. see Note this is different from an array of pointers.

Q: what would you see if a TCP socket server has a full queue
%%A: TCP requires handshake, so if server is unable to accept a request the client would know it. Exact details are not important to me.
%%A: connection refused?

Q: what STL algorithms did you use?
%%A: foreach(), find(), copy_if(), transform(), reverse(), sort(), replace_if, remov_if

Trex QnA IV #low-level C

Q: false sharing? cache coherence? cache line?

Q5: 3 threads in my process, and one of them calls fork(). What are the threads in the child process and which thread will be running?
Q5b: what potential problems do you see?
%%A: some resources like locks could be in a bad state

Q: how do you start a thread? %%A: pthreads_create()
Q1: how do you start a process? %%A: fork()
Q1b: what happens to the parent’s signal handlers, file handles etc

Q: how does the parent process wait for the child process to end?
AA: wait()

Q: sigkill vs sigterm?
%%A: can’t catch sigkill

See other questions discussed in unix signal #Trexquant IV

Q: why we need isnan(myFloat) rather than if (myFloat == Nan)
Q2: I have a float variable1=20180213, and I cast it to int. What’s the int value?
Q2b: two floating point numbers are both very close to 1. In fact they are the closest possible pair. What’s your estimate of their difference?
Q2c: what’s the representation of a float object?

## c++topics seldom quizzed

(master -> pearl)
some low-level details I thought would be popular but seldom asked:
* L-value
* iterator types and implementations
* static variables outside classes
* implicit acts of magic by compiler
* array and cStr – syntax, memory, … the gory details beyond the basics
* template specialization
* ref/pointer typedef inside  templates
* non-dummy-type args in template
* MI
* enum
* exception spec
* C integration
* pimp
* fwd declaration
* namespace
* linker
* extern
* double pointers
* hiding rule
* swap – all the important usages and no-fail
* overloading and  method resolution
* casting and conversion
*** OOC and  conversion ctor
— “mid-level”
* boost Any vs Variant
* i/o stream
* regex
* file access (including random)
* serialization
* memory leak detection
* details of boost thread
* boost smart pointer beyond the shared_ptr
* std::string details

C++ ICE mkt-data – some of the more difficult questions

Q: you said you write code on Windows, but production platform is linux, so how do you test your code?
Q: difference between a C struct and a C++ struct?
Q: have you used memory leak detectors?
Q: How do you link c and c++ code? dlopen()?
Q: have you used memory leak detectors?
Q: scope resolution operator?
Q: default constructor?

Q: what other things are synthesized?
%%A: dtor, copier, op= but c++11 add some move operators
A: indeed, c++11 would synthesize 1) move ctor and 2) move-assignment operator under strict conditions. See

Q: given template<typename T> void f(T a, T b), can f(3, 0.8) compile?

Q: how do you use gdb to view a core file?

Q: write a sqrt(int) function without using the math library.  Estimate to 0.01 precision.

Q: UDP vs TCP?
A: virtual circuit. Single remote socket. In contrast UDP can send to multiple receivers efficiently – broadcast or multicast. A: transmission control, with data loss prevention

Q: what’s wrong with multiple inheritance? How do you deal with it?
%%A: diamond problem. I don’t use virtual inheritance. I use MI when base class is an interface without any field.

Q1: how do you create a thread in c++?
A: std::thread is RAII so the constructor starts the thread, and the dtor must run after joining or detaching.

Q1b: Have you used posix_thread?
A: it’s a c library, so no constructor magic. Probably some pthread_something() function. Correct! pthread_create()

[12]back-scan any container,print`every Other item #MS

Have I overspent my time on this once-asked question?

The umbrella question — write a utility function to iterate any container and print out every Other element backwards?

Good coding practice! I think this is all about iterator syntax knowledge (my weakness) not algorithm (my strength)!

Note this is really about knowledge not  coding abilities. QQ not ZZ.

Iterator declaration is a can of worm 😦 I might need to give up on this.

#include <iostream>
#include <vector>
#include 	<list>
#include <set>
using namespace std;

template<class _InIt>  void printAlternateItem2itr(_InIt _First, _InIt _Last){
	bool flag = true;
	// if the iterator is from rbegin, then ++ would reverse it!
	for (_InIt it = _First; it != _Last; ++it, flag=!flag) {
		if (flag) cout << *it << ' ';
	cout << endl;
template <typename CONT> void printAlternateItemBackward(CONT const & cont) {
	printAlternateItem2itr(cont.rbegin(), cont.rend());
int main() {
	//vector<int> cont = { 11,2,3,4,5,6,7,18 };
	//list<int> cont = { 11,2,3,4,5,6,7,18 };
	string cont = "0123456789a";
	set<int> cont2 = { 11,2,33,44,55,66,77,88,99 };
	int arr[] = { 11,2,3,4,5,6,7,18,9 };
	int size = sizeof(arr) / sizeof(arr[0]);
	printAlternateItem2itr(arr, arr + size); //forward only

Q: is comparison defined on all iterators?
A: now I think linked list doesn’t. Now I think only random access itr does.

%%Q: what’s the signature of STL find()? I will use those declarations of iterators in my function. (Actually the map and set containers have member functions find() outperforming std::find)

%%Q: from a const container, can u get a non-const iterator?

Q: why don’t you take a container as input? Why must you take iterators?
%%A: it’s more common to take iterator, but in this case container will do. All containers provide rbegin() or begin() including string. Raw array doesn’t but the iterator increment won’t work for raw arrays anyway.

Separate question
Q: OO design — how would you represent Order state transition graph in an OMS?

3c++London bbg algo IV #all about array

Q: given a string of characters, find the longest “run” of any repeating character.

Q: given an array of integers, and a target, determine if there’s any pair that add up to the target. Return true/false.

Q: maximum profit problem. Given a time series of historical spot FX rates, find the maximum possible trading profit by exactly one buy one sell.
A: I have seen this many times. First write pseudo-code.


Q: a vector needs to allocate N instances of Account but Account has no default ctor, but it just works. How does the compiler achieve it? (Actually it won’t compile if compiler can’t synthesize the no-arg ctor)
A: indeed the call to array new would prevent the vector concrete class from compiling due to SFINAE rule or something like that. (Java and c# would use type constraints instead.) The compiler must be using 2 separate lines – one to allocate raw memory, the other to initialize the object.

However, when is vector internal array allocated by array new? I discussed with Ashish but found no answer.

Q: why did you say you needed to write your own smart ptr?
A: super simple one, just to deal with some issue of the raw ptr… probably dangle pointer, by overriding the deref operator

Q: why would anyone use unique ptr when shared ptr is general purpose
A: threading…
A: some pointee objects are designed with sole-ownership

Q: is the lambda functionality doable in c++98? what is the c++98 equivalent?
A: some functor with a challenging syntax I can’t remember.

Q: OK you don’t use c++11 at work, but do you hack around at home?

Q: why is  the bid/ask spread much wider in options than the underlier?
A: must be the risk to the writer. Competition didn’t drive down the bid/ask spread like it did in FX and cash equities.
AA: delta hedge adjustment can’t be done every second. Before the next adjust, the risk to the writer (market maker and quoter) would be quite high.

c++IV Art@Click #Jens

Q: buffer overflow?
%%A: avoid arrays, use vector
Q: XOR usage?
AA: usages? easy to google
Q: why bitwise shift?
%%A: mostly an optimization as far as I know, but the compiler probably translates integer multiply/divide already.
AA: usages? easy to google
Q: what’s wrong with pointers?
Q: dangling pointer?
Q3: what are the common exceptions in c++?
%%A: c++ has a few standard exceptions and a lot of UB; java has lots of standard exceptions and no UB. q(new) and dynamic_cast…
Q3b: undefined behavior?
%%A: much worse than exceptions or error codes
%%A: perhaps fairly consistent on one platform, but I know writing beyond an array’s limit is indeterminate. See [[c++ debugging)]
Q: exceptions – why do you not want to use it in your API?
%%A: can of worm. If I throw I can’t control how clients use this API. What if it’s thrown in a dtor? What if they don’t catch by reference? What if they catch a sliced one or a copy rather than the original exception object I want them to get? What if they catch by pointer and try to delete or forget to delete? Java cleaned it up.
%%A: I don’t see a lot of well-regarded API’s exposing exceptions
%%A: there’s performance cost
A: the best practice has always frowned on exception specifications. C++11 favors “noexcept”
A: now I think we should be consistent throughout – either throw exceptions consistently or never.
Q: memory leak – what is it and how do you deal with it?
%%A: valgrind replaces malloc with …?
%%A: provide class-specific op-new (and delete), which is safer (see effC++) than a customized global op-new. Add your own house keeping code therein…
Q: how is semaphore different from a mutex
%%A: I think a mutex is more basic and usually provided by the kernel (For a userland thread the thread library not the kernel must provide the mutex). I guess the counting semaphore is implemented using mutex + condition variables, since the semephore may need to inform the waiting threads.
Q: preprocessors?
%%A: 3 usages in my projects – #includes, macros and conditional compile. Now I think template meta programming also uses a lot of macros.
Q: stack trace?
%%A: very useful, that’s why java, c#, python, perl provide it, and GDB too.
A: [[safe c++]] shows simple and robust technique to build a stack trace upon assertion failure
I said many times “I’m philosophical about that” – meaning “it’s controversial IMO and I have my views which may look naive or extreme or eccentric”

c++11 QnA IV 3arrow

Q: In a move constructor, is the parameter “x” an rvalue reference? is there another rvalue reference in the call?
%%A: x is a rvr, but as a variable is an l-value expression since it is named and has a Location.

Q: What’s an rvalue reference actually, like a std::string && rvr1
A: I feel it’s similar to a regular reference variable and often treated as a pointer. Since “pointer” has multiple meanings, I would not say that. I speculate that compiler treats rvr1 as an special alias to the original object. A special name plate on the memory location. Compiler knows to treat the object-behind as suitable-for-stealing.

Q: what’s lockfree? How did you make it work in your projects?
A: see my blog about atomic{int}

Q: What part of the boost thread library did you use?

Q: for-loop in c++11?
AA: work for C-style arrays, initializer lists, and any type that has begin() and end() functions defined for it that return iterators.

Q: Why did you implement your own smart pointer and wrapper over int?
A: to avoid uninitialized variables. See post on uninitialized ..

Q: Can ctor throw exception? Why do you say it’s not best practice?
A: now I think it’s not necessarily best practice. Exception is the only way constructors can signal failure.

Q: What kind of algo is qsort? Average and worst runtime complexity?
A: average nLog(n), worst case n^2

Q: Recursive vs iterative, which is faster?
A: comparable, but space complexity lower for iterative?

Q: How did you use parallel processing in GS?
A: data parallellism, threading, and other techniques. Coarse-grained is ideal.
A: i guess pipelining parallellism is also relevant, using task queues

Q: (rarely quizzed) Translation lookaside buffer

Q: mutable keyword’s usage? How about in c++11?
AA: closure – captured variables can be modified if “mutable”.

Q(seldom quizzed): noexcept
AA: both an operator and a function specifier…


c++iv: Jump#2

Mostly obscure QQ type of questions. I feel i may have to give up on some of the very low level (perf optimization) topics. I feel java and c# interviews are not so low.

Q: Stack overflow – who can detect it and print an error msg? JVM can do it but what if there’s no VM?

Q: What data type would you use for the tasks in a thread pool??
(I find this question too advanced. c++11 offers Futures…)
%%A: look at pthread-create. a func ptr taking a void ptr

Q: After malloc(), how do you cast the pointer to MyClass* ? Do you call the ctor? How?
(This is asked again by Alex of DRW)
A: placement-new?

  • Inter-thread communications in thread pool – how does it work?
  • Thread pool — Your resume mentioned your home-made thread pool? How?
  • Boost::any, boost::bind, boost::function
  • CPU cache – how do you use it to improve performance? Any specific techniques?
  • Stack size – who controls it? at Compile time or run time?
  • Shared ptr – how is it implemented?
  • Scoped lock – what is it, why use it?
  • Your bash shell customizations as a cpp developer?
  • $LD_LIBRARY_PATH — what is it?

c++Chicago/Sing (Jump) IV Aug 2012

Q: UDP vs TCP diff?
%%A: multicast needs UDP.
%%A: UDP is faster – no connection setup/teardown no error check no ACK, no sequence number; shorter emvelope

Q: How would you add reliability to multicast?
%%A: sequence number

Q: How would you use tibco for trade messages vs pricing messages?
%%A: the trade msg must be delivered reliably to back office?
%%A: one of them is real time?

Q5: In your systems, how serious was data loss in non-CM multicast?
%%A: Usually not a big problem. During peak volatile periods, messaging rates could surge 500%. Data loss would deteriorate.

Q5b: how would you address the high data loss?
%%A: test with a target message rate. Beyond the target rate, we don’t feel confident.
A: tune the tibco reliability parameter —

Q7: how is order state managed in your OMS engine?
%%A: if an order is half-processed and pending the 3nd reply from ECN, the single thread would block.

Q7b: even if multiple orders (for the same security) are waiting in the queue?
%%A: yes. To allow multiple orders to enter the “stream” would be dangerous.

Now I think the single thread should pick up and process all new orders and keep all pending orders in cache. Any incoming exchange messages would join the same task queue (or a separate task queue) – the same single thread.

3 main infrastructure teams
* exchange connectivity – order submission
* exchange connectivity – price feed i.e. market data. I think this is incoming-only, probably higher volume. Probably similar to Zhen Hai’s role.
* risk infrastructure – no VaR mathematics.

c++buy-side data support IV (wq)

(world quant?)

local vs my in perl?
what’s bless in perl?
multiprocessing vs multithreading modules in python?

From a simple salary table, select the row with the 2nd highest salary. Address in my blog on top9

toss a dice 3 times. What’s pr(getting 3 different numbers)

Q: advantages of operator overloading?
A: sometimes you have no choice, like op= and Smart pointers
A: eg: STL containers offer bracket operator
A: eg: iterators offer increment
A: if you have a special_number class, you would consider +/-

Q: vector vs linked list

Q: difference between private and protected keywords in c++? Seldom quizzed!
A: P613 [[c++primer]] says

  • members of the subclass are unaffected by these priv/prot derivation-access-specifier. (Instead, they are controlled by the base class member’s priv/prot classification.)
  • users and children of the subclass are affected!

Q: Scan a multi-line text file just once to pick a line at “random” i.e. where each line has the same probability. Not well-defined problem. Don’t spend too much time.
A: save the lines in a vector. At end of the scan, we know the vector size. Pick a random non-negative int below vector.size()


c++ stream — IKM findings

——tellg and tellp? is a short explanation.

tellg(void) and tellp(void) both return their pointer’s position
ostream& endl (ostream& os);
stream::rdbuf() changes the filebuf…
endl – flush() implicitly
If your variable to “populate” is an int, then extraction operator stops when hitting ….”any character that couldn’t be part of an int” which is not limited to white space.
—-which stream classes can be used for writing to a file
——which ios modes are used for reading a file

c++ low-latency connectivity IV (nQuant) #2

This IV is heavy on low-level QQ in C/C++. Such obscure knowledge won’t help GTD and is not significant zbs. They may improve your design though.

Q3: Memory alignment – what if on the stack I declare 2 char variables? See post on memory alignment.

Q3b: what if I have 2 char fields in a struct?

Q3c: I have two 64-bit ints, one misaligned. When I use them what problems will I have?
A: not much performance penalty. See

Q1: If inside a member function I call “delete this”, what happens?
%%A: what if this “this” points to an object embedded as a field of an umbrella object? The deallocation would happen, but the destruction of the umbrella object may again deallocate it? This is confirmed in the FAQ (
%%A: how do we know the host obj is on heap, stack or global area i.e. data section.

Q1b: To achieve heap-only, my class has private ctors and private op= and a static factory method. Will it work?
%%A: according to moreEffC++ P146, I would say yes, with certain caveats.

Q2: What’s reinterpret_cast vs dynamic_cast vs static_cast?

Q2b: What other casts are there?

Q: Placement new – can I use the regular “delete”?
%%A: probably no. Need to call the dtor manually? See P42 moreEffC++

Q: How does tcp handshake work? (I don’t know why this nlg is even relevant)

Q: Some tcp parameter to speed it up?
A: larger TCP window size?

Q: tcp client to specify a non-random port? See post on bind()

Q: If a c++ app runs fine in debug build (compiler optimizations removed), but crashes in release mode, what guesses/clues do you have?
%%A: conditional compilation, like in my c# project
%%A: the compiler optimization leads to unusual execution speed between 2 threads, and cooks up a rare corner case
%%A: I have seen assertions turned on in debug build (a debug STL can also be used), so we know one data file F1 is unusable, and another data file F2 is usable. In release build, someone else tries F1 and it crashes somewhere else.

See c++debug build can modify app behavior!

nQuant c++IV #1 #monitoring

Overall, I remember nQuant IV was rather low-level and heavy on optimization. Mostly QQ.

Q6: how could do you implement a userland thread?
%%A: setjmp and longjmp, as in early JVM

Q6b: how? I feel better be modest and offer my tentative guesses.

Q6c: how is setjump different from goto? Seldom asked!
AA: and

Q: by default, is a linux mutex cross-process?
%%A: I guess the mutex in pthreads by default isn’t. Outside linux, the windows mutex is cross-process.
AA: Beyond the default, linux mutex can be cross-process, by using shared memory —

Q: in linux, what’s the difference between a process and a thread?

Q: start 5 copies of the current process, using fork? (Can use the example in [[head first c]] )

Q: If a variable in (2-process) shared memory is marked volatile, is it a reasonable usage of volatile keyword?
AA: now i think so. Similar to a variable writable by a temperature sensor. shows use of “const volatile” on a variable in shared memory.
AA: [[moving from c to c++]] section on Volatile (P75) seems to agree

Q: what’s a limitation of the select() system call when there are too many sockets to check, and each messages (~ 2KB) is important.
A: select has max socket count. Use epoll() —

Q: what linux command to monitor memory usage by a given process, showing size of heap, stack, text, even broken down to shared lib vs static lib
A: cat /proc/{pid}/smaps
A: pmap -x {pid}

Q: given a one-line c program “while(1);”, launch it and /usr/bin/top would show 100% cpu usage. What does it mean?

Q: what’s inside a socket? My socket book has detailed diagrams.

Q: can a socket be shared by 2 processes?
AA: Yes. See

———I feel most of the questions below are rarely asked.

Q: how many sockets can a single process open? Not too sure. A few hundred?

Q: what linux command to monitor network performance?
%%A: Beside netstat, I have seen tools that report error rates that indicate saturation
A: ss


Q: how to remove the word “option” from a resume, unless it is a sub-word? Use perl or python
%%A: Word boundary symbol?

Q: when a user land thread makes a syscall, what’s the implication?
%%A: the thread enters kernel mode?

Q: what’s offered on Layer 2? Can IP simply operate on top of physical layer without Layer 2? Too deep and seldom asked.
A: ethernet is a L2 technology.
A: Each device on a network has a hardware address or MAC address, used by the data link layer

c++IV data analyst(WorldQuant

Struct base{
char * buffer
base(){ buffer = new char[1000]; }
}; //how do we improve this class?

What if the new() throws exception

Q: if you make buffer a smart array then what do you do with the big3?

Q: diff between scoped_array vs shared_array?

Q: what if I have a derived class without virtual dtor?

base * a = new derived;
delete a;

Q: What if I make derived a virtual subclass and have a derivedDerived class?

c++buy-side data support IV (wq) – phone round

Q: inline function vs macro. Not on my Tier 1/2
%%A: macro is frowned upon. Inline is a hint to compiler

Q: reverse a single linked list in-place. How many temp variables needed and how?
A: 3. I wrote this, in this blog

Q: volatile keyword in c++
A: used to be hardware-related. Also used for threading? Not according to a stackoverflow post
Q: throw exception in constructors? Best practices?
A: memory cleanup needed … JVM/CLR handles it!
Q: given an unsigned integer, how do you test if it’s a power of 2.
A: x-1 would be all-1…

2013 Citadel IV – c#, C++

Q: System.Array.CopyTo() vs Clone()
%%A: Clone() is declared in a supertype IClonable, whereas CopyTo is only in Array class – confirmed
%%A: Clone() is controversial – confirmed.
%%A: Clone() returns a new object whereas CopyTo requires a target array of the correct size to pre-exist – correct

AA: Array class has  a static method Clone(), but I feel the real important point is the Clone() controversy.

Q4: What does the “…” mean in C++ catch(…)?
%%A: If the troublemaker has no (not empty) exception spec, then “…” means catch-all. Any type of exception can be thrown and will be caught here
%%A: if the troublemaker has an exception spec of type B, then “…” means all subtypes of B. If another  type of exception is thrown, then unexpected() triggers, with the catch(…) ignored. Tested 🙂
A: i think my answer was correct.

Q4b: What’s the c# counter part?
%%A: catch(Exception) or an empty catch{/**/} — confirmed

Q3: delegate — what is it and what’s the usage?

Q3b: what’s the c++ equivalent (or closest)
Q: What design patterns are behind the c# delegate?
A: for multicast …. observer
A: for unicast … command? The delegate instance usually has a host object
Q: how do you manage memory leaks?

BNP (NY) FX algo trading IV 2012

Tick data needed for … back testing, analysis? Quants use R, matlab etc to analyze data. IT don’t use those.

Q: how can you help my desk make more money?

Q: from a low-level interviewer — describe to me a challenging technical design (and expect me to drill in).

Q: We know the drawback of auto_ptr. Now write an auto_ptr template class spec (without function bodies) with private op=()

Q: describe some threading challenge in your low-latency system.

Q: how would you use pigeons for IPC (possibly across machines)?
Q: what’s a unix domain socket?

Q: is Throwable checked or unchecked exception?

Q: how many incoming/outgoing orders a day?
Q: peak incoming order rate

(I feel they noticed my pretrade pricer as it’s similar to their market making engine.)

Q3: what pretrade pricing rules did you have? Describe how they work in real life
Q3b: what’s the peak price update frequency?

Q: in your pretrade pricing engine, how many messages do you send out each day?

Q: how does the pretrade pricing system interact with other systems?
Q: are the conduits more retail or institutional?
Q: how does the asset valuation work?

%%Q: what do quants here do differently from quants in der pricing?
A: tune parameters; analyze data and come up with strategies; Sounds simple but a lot of work.
%%A: constantly improve the strategies and parameters.

%%Q: 20,000 euro loss would be realized loss?
A: yes

%%Q: what if multiple strategies trade the same currency pair without knowing each other?
A: multiple live strategies can trade the same pair. They should be designed to minimize correlation and know each other.

c++/vol IV: FX risk (barcap@@) mid2012

Q: basic exception guarantee
Q: stochastic vol vs local vol?
Q: what’s RAII? What are the major classes you know using RAII
%%A: smart pointers, locks, stl containers, strings??

Q: what synchronization classes are there in c++?
Q: can a static member function be const?
%%A: no. the const is on “this”

Q: is it ok to mark a field mutable
%%A: I think so. student.getAge() can modify lastAccessed timestamp.

Q: what are the option models you know

Nomura FX option IV #Ldn video link

Q: what are the products traded on your desk
%%A: stock/ETF/index options + var swap for flow vol. For EFS, there are a lot – digital options, barrier options, Asian style options, structures with 2 underliers
Q: how do you monitor the barriers – discrete or continuous or …?
Q: what does a typical quant library API function looks like?
Q: You said c++ is more challenging, but what technical challenges do you see using c++ compared to java?
(Now I would say pointer, memory mgmt, STL, undefined behaviors…)
Q: how is a libor yield curve constructed?
Q: what’s the rationale for using swap rates to derive spot rates for a long tenor?
Q: what’s the rationale for using libor futures rates to derive spot rates? 
Q: for risk management, what features of the vol surface are measured/monitored?
%%A: skew bump, tail bump. Wings are known to be problematic.
Q: did you work on PnL explain?
Q: Our trades are often long gamma. What happens to their thetas?

c++ Push all zeros in array to the end #easy

Basic programming exercise

#include <cstdlib>
#include <iostream>
#include <iterator>
#include <assert.h>

using namespace std;
int a[] = {0,0,-1,2,0,4,0,0,8,0};
Push all the zero's of a given array to the end of the array. In place only. Ex 1,2,0,4,0,0,8 becomes 1,2,4,8,0,0,0
int main(int argc, char *argv[])
   size_t size = sizeof(a)/sizeof(a[0]);
   copy(a, a+size, ostream_iterator<int>(cout, " "));
   int left = 0;
   int right = size -1;
   while(left < right){ if (0==a[left]){ while (0==a[right]) --right; if (left >= right) break;
          swap(a[left], a[right]);
   cout<<"\n new: \n";
   copy(a, a+size, ostream_iterator<int>(cout, " "));

c++highly parallel numerical programm`IV(smart ptr, threading…

These are mostly QQ type. Jap firm

Q: What are the differences between win32 and linux threading Implementation? I probably won’t spend time reading this.

Q: given a bunch of 10-year old linear algebra c++ functions (using many VD or MD templates as function inputs), how would you go about extracting and packaging them into a DLL? No experience. Not on my Tier 1/2.
%%A: stateless
%%A: pure functions.
%%A: Thread safe
%%A: remove code duplication
%%A: for each function, there should usually be default parameters, so we can call it with 2 args, 3 args, 4 args etc
A: function parameters should not be templates. Ints, double are probably fine. DLL interface is defined by the platform, not the language.

Q: what’s wrong with boost libraries?
AA: (STL is fine) many of them aren’t proven — just 10 years

Q: Since you said shared_ptr is the most popular boost module, how is reference count done in heavily parallel programming
%%A: for regular shared_ptr, thread safety is a big design goal, so probably fine[1]. For intrusive_ptr, the pointee class must expose certain mutator methods, which must be made thread-safe by the pointee class author, not boost authors

[1] isn’t correct. The testing on shared_ptr thread safety isn’t sufficient for large number (thousands) of threads. See


c++low latency phone IV #MS-shanghai

I think this is all QQ… i.e theoretical knowledge. Not really harder than the mvea interview. Easier than the CVA interview.

Q: why we should not throw exception from dtor? Why do you say sometimes you can break the rule? See throwing dtor: %%justified use cases
%%A: if i have a utility routine that may throw, and I want to use it in my dtor, we should assess the danger. If we know entire process should crash under this condition, whether this dtor throws exception or swallow it, then it’s fine to use that routine without try/catch. Even without double-exception situation, the default behavior is std::terminate()

Q: divide by zero — is that an exception?
%%A: yes in java but UB in c++
AA: UB in c++

Q: is there something you can do in C but can’t in c++?
%%A: I guess you mean “C code uncompilable under c++ compiler”? I don’t think so.
A: “include <stdio>” won’t compile in g++
%%A: in pure-C environment if you receive a pointer at run time and it’s known to point to heap, you can call free() but in a C++ environment, that pointer may be created by new/array-new so free() is problematic.
A: hints that if a C source code has no function prototype, then c++ compiler will complain.

Q: at what threshold of latency requirement would you switch from java to c++?
%%A: 100 μs. but I think nowadays java can rival c++.

Q: singleton — how would you implement
%%A: no friend class; declare but not define copier/op=. Provide a static method getInstance

Q: size of an empty c++ class’s instance
%%A: 1 byte (Correct !

Q: diff between struct and class
Q: can you implement inheritance and polymorphism in C?
%%A: yes. Most c++ features (until exception) used to be converted to C source code.
Q: what’s complete vs partial specialization of template? (Jargon question)
Q: what happens to stack when an exception is thrown?

Q: what’s your reaction when you see “delete this” in a program?
A: After that, need to be careful not to reference anything in the class, so as to avoid dereferencing a dangling pointer.


c++Citi (Changi Biz Park) winows IV (method hiding

Q: Base class has non-virtual float f(int); Derived class has void f(int);
Base& ref = aDerivedInstance; ref.f(333) invokes which one?

My test proved — base and derived classes’ f() can both be invoked in the same program, but on 2 distinct variables (Base vs Derived). I believe compiler/runtime can distinguish the 2 functions. Remember this is no inheritance nor redefinition — If you only have a Derived variable, then the Base f() is hidden, regardless Base f() is virtual or not.

If Base and Derived both define methods of the same NAME f(), then Derived either overrides/redefines or hides Base f() functions. I don’t think you could get to the Base versions via a Derived object — Base version can’t coexist in Derived with Derived version. But When would method inheritance actually work? Well, only if D doesn’t contain a method of the same NAME. As soon as it does, all B methods of the same NAME are either overridden or hidden.

Incidentally, EffC++ P 114 points out that c++ compiler condones lots of ambiguities and only generates a COMPILER (not runtime) error when you write a call that’s ambiguous. Javac compiler can also complain about ambiguous method calls

Incidentally, if you call a declared but undefined func, you get a linker error, not a compiler error. EffC++ P116.

Q: Is option delta always between 0 and 1?
A: no

Q: write a c++ singleton

Q: write a reader/writer lock class given a basic mutex class. I don’t feel confident since there’s no one to help review my code.
%%A: lock release should be in dtor. Therefore, acquire should be in ctor.

c++/java MS commodity IV – 2010

Q: SQL when would u turn on dirty read?

Q: can you tell me some of the drawbacks of stored-proc?

Q: challenges in database refactor?

Q: technical/project challenges you faced in your career?

Q: how do you put across your argument in that challenging situation?

Q: when I enter in a shell, what happens?

Q: 3 threads are adding/remove/reading single elements in a hashmap. How do you optimize synchronization?
A (now i think): i guess lockfree is perhaps the best
A: concurrent hashmap with each segment holding multiple keys

Q: but if remover and reader use different keys, then why should they wait for each other?
A: they might hit the same bucket

Q: what other maps beside hashmap?
A: treemap, a red-black tree

Q: what’s a red-black tree?
A: perhaps a balanced tree

Q: how is it balanced?
A: perhaps by shifting the root?

Q: What are the list implementations?

Q: is insertion faster in linked list or array-based list

Q: is insertion faster in linked list or hashmap

Where is c++ used? quant lib for risk, PnL and trade booking. Is c++ going away? no.

2 main specializations — physical scheduling + risk including pnl attribution

1st SCB IV #commod #private inheritance

Q: you have identical rows in a SQL table. How do you remove the unnecessary rows?
%A: select into a new table, then overwrite the old, but this involves a lot of disk space and IO
%A: perhaps delete where (select count(*)…) > 1 and rowid > 1 — using oracle rowid

Q: given a long string consisting of the 26 letters A-Z, print a histogram like A:865 times, B:9932 times….

Q: copy a vector to another vector. What if the source is very large? Correct — you get reallocation, so how do you avoid that?
%A: either reserve or resize() the target vector with sufficient capacity. However, the 2nd option default-constructs a large number of payload objects!

Q: when would you use private inheritance?
A: This is rarely needed or quizzed. Not on my Tier 1/2. [[effC++]] P204 has an example of MI and also an example of private inheritance — a public inheritance of a pure interface and also a private inheritance of a concrete class. However, Google style guide strictly states that private inheritance should be replaced with composition.

[11]Miami exchange HFT IV

First of my 10+ HFT style QQ interviews, where the QQ topics were completely alien to me.

Q: 3 no-choice scenarios to use initializer list. Efficiency is a 4th reason.
%A: const or reference field, or if one of the fields has no op=
%A: if a base class lacks a no-arg ctor
A: if a data member’s class lacks a no-arg ctor
A: what if a data member is a reference-counted class like a shared_ptr?
A: what if a data member’s class keeps track of instances constructed

Q: What exchanges send you market data feed?

Q: outline a ref-counted copy-on-write string class, showing all the function declarations
See separate post

Q: how do you see what system calls a running process is calling?
%%A: strace for linux
AA: also DTrace/truss/tusc on other unix variants.

Q: RTTI is too slow, but somehow (can’t remember the context) we need to tell what class (in a hierarchy) this object is. How do you achieve that? See clever use of enum(char?) in demanding c++ app

Can’t remember the exact question….
Q: tell me a clean solution to support cout<<myDog; where Dog/Cat/Ant/.. classes are derived from Animal
Hint from questioner — you can edit Dog class.
A: see c++friend function calling a virtual method

P156 [[essentialC++]] has some simple tip

Note overloaded operator is like a method and can be virtual — However, our operator<< has to be a friend!

2011 Pimco c++ #+perl/SQL #done

Many obscure QQ questions. Be selective what to study!

Q: diff between malloc() and new()?
%%A: must cast void ptr; must call ctor
A(hind sight): malloc need to be told the size. In contrast. new() relies on knowledge about the class
A(hind sight): array new can be done with malloc too
A (hind sight): new can be a (static) method, therefore inherited or hidden.
A: q(new) would put some housekeeping data in a header. Therefore, you can’t use free() on a new() ..

Q: ok, so malloc doesn’t call ctor, but can I pass the malloc void ptr to a ctor for initialization?
%%A: placement new will initialize a block of memory without allocation.
%%A: it’s not common. C++ language doesn’t encourage this operation.
A(hind sight): ctor doesn’t take a ptr argument?
AA: placement-new — Also see

Q3: can you call a dtor explicitly?
%%A: yes though not a good idea. See C++ FAQ
A (hindsight): placement delete

Q3b: when would yo do that?
%%A: when i want to free a large block of heap memory as early as possible, and the dtor is not scheduled to run any time soon. But without delete() the heap memory isn’t freed. Probably delete can achieve the same purpose without looking ugly.
%%A: again, not  common and not encouraged by C++ language. I don’t think i would ever do that.
A(hind sight): placement new? Correct 🙂

Q5: can a dtor throw exception as the last statement?
%%A: no cos the dtor can be invoked as part of stack unwinding

Q5b: so what?
%%A: stack is unwinding due to another exception, and now your dtor creates a 2nd exception object. System is going to lose critical information in the 2 exceptions. The original exception handling flow is halfway through.

Q: given an instance of an absolutely empty class, can I downcast a ptr (or reference) to it?
%%A: assuming this class inherits from another empty class, you can’t since there’s no vtbl.

Q4: can you specialize a template with a ptr type as the type argument?
%%A: yes vector of raw ptr is common

Q4b: what must this template do to accommodate ptr template arguments? Too advanced and not one of my Tier 1/2 specializations
%%A: handle dtor, assignment and copier.
%%A: any memory-management operations must be customized. Default behavior is not good for ptr type arguments

Q: which part of c++ is most interesting to you?
%%A: low level access. Few other languages provide the low-level access

The remaining (perl and sql) questions are less daunting.

Q: perl pass an array by reference into a sub?
%%A: you can pass the address of the array. Array can be modified in-placer by the receiving sub

Q: chomp?

Q: perl open a file in append mode?
A: use “>>”

Q: when would you create a non-clustered index?

Q: select 2nd highest salary from a salary table?

Q: if my query need all 3 columns of an index (id, name, salary), how would you order the 3 columns when creating the index? Suppose salary has the highest selectivity
%%A: salary first

slist: remove consecutive dupes #Macq

struct litem {
     char data;
     litem* next;
void myDelete(litem * i){
  delete i;
int remove_consecutive_duplicates( litem*& list ){
  vector trash; // collection of bad nodes' address, to be DELETE'd
  litem* keep = list; // this pointer only points to “good” nodes to keep
  for (litem* p = keep->next; p;  p=p->next ){
    if (keep->data != p->data) {
      keep->next=p; // often unnecessary, but very cheap
  keep->next = 0; // keep is now the last good node. It may or may not point to null. This  is cheap insurance.
  int ret = (int) trash.size();
  std::for_each(trash.begin(), trash.end(), myDelete);
  // now, trash.size() == ret probably, as trash holds a bunch of stray pointers, but just in case size changes in the foreach loop, we save the original size in advance.
  return ret;
void dump( litem*& list){
    for (litem * p=list; p; p=p->next){

data< “;
int main23(){
   litem* a = new litem();
   litem* a2 = new litem();
   litem* a3 = new litem();
   litem* b = new litem();
   litem* b2 = new litem();
   litem* b3 = new litem();
   litem* b4 = new litem();
   litem* c = new litem();
   litem* c2 = new litem();
   litem* c3 = new litem();
   a->next = b;
   b->next = c;
   c->next = c2;
   c2->next = a2;
   a2->next = b2;
   b2->next = b3;

IV at MS-IRD (java) + Imagine c++ #done

Q: implement getAngleBetweenHourAndMinuteHands(byte hr, byte min)

Q: implement getFirstNPrimeNumbers(int howMany)

Q1: Given a list of 99 random integers (uniqueness not guaranteed), write a function to find any pair that adds up to 1000. The function takes 2 arguments – a target int and a list of int.
%%A: I blogged about this. Build a hashset to hold all 99 numbers in 1st pass. In 2nd pass, for each number, compute the “complement” and look for it in the hashset.

Q1a: what if the list is pre-sorted?
%%A: no change. Same performance. The pre-sort doesn’t help.

Q2: how do you price an IRS? I will assume an existing vanilla IRS
%%A: the existing contract’s fixed rate is compared to the prevailing swap rate. The difference represents a periodic cash flow that’s fixed! Just discount that to PV.

Q2a: what if you have a discount curve?

Q: Given a singly linked list, write a recursive function to reverse the list

Class Slist{
Node * head;
Node * tail;

Q (ez coding question): for an array of characters (null-terminated string), write a (recursive or iterative) function to reverse print it.

Q: given a simple class with an int field, implement pre-increment operator and post-increment operator
A: I have never done this in work, but the syntax is easy to find on-line.

Credit Suisse tick data C++IV

Mostly QQ!

Q: auto_ptr vs scoped_ptr? See my other blog post

Q: when did you use a binary functor?
%%A: provide that class to a template to concretize it

Q: if I have an empty class, what’s the size of an instance?
AA: 1 byte

Q: offsetof() macro in C?

Q: ref vs ptr

Q: when is copy ctor implicitly invoked?

Q: given a vector of ints, how do I add 1 to each of them, in-place?
%A: for_each(), transform()

Q: what are functors?

Q: did you use priority queue?

Q: in network programming, how Did you use select?
%%A: My system used it but I didn’t study it in-depth

Q1 (actually easy): Anything wrong with a vector of references
%%A: won’t compile

Q1b: can I put references into containers?
%A: never seen it.
%A: I know it’s sometimes ok to put pointers in containers, or const pointers. Since references are very much like pointers, it might be ok
A: compiler breaks saying “pointer to reference is illegal”. I think it’s because iterator of vector is a regular pointer to the underlying_type. If underlying_type is an int ref, then the iterator would be a pointer to an int ref.
A: In STL source code there’s

typedef T* pointer;

If T is int&, this code won’t compile.

[11]Cantor/eSpeed c++ #manyQ

Mostly knowledge-based QQ questions. I need to be selective what to study.

Q1: The reverse is common but when do we provide c wrapper around c++ classes?
A: internal implementation is c++ but clients need C API

Q1b: can c call c++ # <—— very common question
%%A: at compile time, c++ code may be uncompilable by a c compiler. CFRONT converts c++ code into c source code until exceptions were added to the c++ language. At run time, if I have object code precompiled from c++, can c call it? I think it’s often possible.
A: check out the C Application Binary Interface. If your C and C++ code are interoperable, it is because your C and C++ compilers also conform to the same ABI.
A: yes that’s what extern “C” is for.

Q: tool for binary code dependency? (I guess the dependencies are dynamic libraries, rather than static libs linked in.)
AA: ldd or objdump. See

Q9: call java from c++, what’re the c++ function(s)?
A: create_vm(), CallStaticVoidMethod(), CallVoidMethod() etc

Q9b: How do I access an int field of a java class?
%%A: if I have a pointer to the java object, I should be able to directly access the int field

Q: how do u implement a singleton

Q: semaphore(1) == mutex?
%%A: no since semaphore in most implementations uses a mutex internally. Functionally they are identical
%%A: semaphore is often cross process. Mutex can also be used on shared memory.

Q: for a const method getAge(), can it return a ptr to a non-const int which is a field?
%%A: i have seen sample code, so probably compilable
A: tricky. P215 effSTL says that inside a const method, all non-static fields become const.

Q3a: what’s the return type of operator*()?
%%A: can be anything, just like operator[], but not void not empty

Q3b: How about qq[ operator T*() ] ?
A(now): is it the OOC to a ptr? Correct. See

Q: if Base class has a virtual method f(int), and Derived class has an overload virtual method f(float, char), is the Base f() accessible via a D object?
%%A: the D f() hides the base f(), but base f() may still be accessible using A::f()

Q: 1 process, 30 threads vs 10 processes * 3 threads each? Assuming there’s data sharing among the threads
%%A: avoid ITC and serialization
%%A (Now): I feel single-process has a single point of failure without redundancy.
A: depends on the IPC cost. If non-trivial cost then favor 30-threads.

Q: how do u change the default fair-share scheduling among threads? #<— uncommon
%%A: I can make some threads sleep or wait. I can control thread-lib-level priorities, but the kernel thread priority levels could be very coarse
%%A(now): if userland thread, then scheduling is done in the thrd lib.

Q: unix performance monitoring?
%%A: jconsole; top; vmstat; perfmeter


Q: Dynamic loadable library. How do we configure the system to load a new version of the library?
%%A: just overwrite the existing *.so file??

Q: how to convert a ptr-to-non-const to a ptr-to-const?
AA: just assign it. The reverse assignment needs const_cast. Tested in g++. I feel this is an obscure technicality.

— communication layer
Q: how do I see syscalls and sockets open by a process?
%%A: truss; lsof; snoop/tcpdump; netstat

Q: practical use of signals?
%%A: kill, core dump, thread dump, suspend,..
A: I used q(trap) to install my signal handler in my bash

Q: what are named pipe? #<—– uncommon
%%A: I think they exist in the file system as fake files. “cat | more” uses an unnamed pipe I believe.
A: now I think I should just say “never used it”.

2011 BGC c++IV #socket #done

Q3: what can go wrong during a write to a socket??? (LG)
Q3b: if buffer is full, will the writing thread block???
%A: by default it blocks, but it’s probably possible to configure it to return an error code or even thrown an exception

Q: blocking vs non-blocking socket?

Q: socket programming – what’s select ?

Q: Should base class dtor always be virtual?
%%A: I would say yes. If a dotr is really not virtual, then it’s not supposed to be a base class. However, SOF mentions: “If you want to prevent the deletion of an instance through a base class pointer, you can make the base class destructor protected and non-virtual; by doing so, the compiler won’t let you call deleteon a base class pointer.”

Q: how many ways to share data between 2 processes? How about shared memory

Q: synchronize 2 unix processes accessing a shared file?
A: named semaphore

select2perform c++questions #ez

Q: given char * const cp = ….; can you do cp[0] = ‘b’
AA: yes. const is about the pointer (no rebinding), not the char pointee.

Q: can friend-class to Derived access Base protected field?
AA: yes in gcc

Q: what are the narrow-character iostream objects?

Q[u]: anything wrong with static_cast(MyClass var2)
%%A: This is a silly question. Bad coding style.
AA: illegal in gcc

Q[u]: if a ctor takes an int arg, can you call it with a char literal?
AA (confirmed): implicit conversion from char to int

Q: can a C struct be subCLASSed?
AA: yes struct differs from class in one way only

Q: if u catch by value, modify the exception object, then do an empty throw all within your catch block, then the does downstream catch the original or the modified object?

Q[u]: what’s wrong with

char * charArray = someString.c_str()

%%A (confirmed): c_str() returns a pointer to const char. Const radiates leftward

Q[u]: when you pass std::less to list.sort(), must you append “()” as “std::less()”?
AA: illegal without ().
%%A: std::less is a class, so we are instantiating it.

Q[u]: can catch(…) be the first among many catchers?
AA: must be last — illegal otherwise

Q[u]: a class template’s static function uses the T as parameter type. Callable without ?
AA: this follows the CLASS template instantiation rule, not the function template instantiation rule. No implicit detection by compiler. You must provide explicit type argument when referring to the class template

Q: bind1st or bind2nd on std::less when used as find_if() filter
AA: here’s the idiom. We are binding 2nd parameter to the literal 1000.
Note std::less is a Class template not function template, so the template type arg is mandatory.